Skip to content

Commit

Permalink
Prefer getEnvVariable in stack-backend
Browse files Browse the repository at this point in the history
  • Loading branch information
N2D4 committed Jul 2, 2024
1 parent c65addd commit fb825e6
Show file tree
Hide file tree
Showing 11 changed files with 34 additions and 16 deletions.
10 changes: 9 additions & 1 deletion apps/backend/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
module.exports = {
extends: ["../../eslint-configs/defaults.js", "../../eslint-configs/next.js"],
ignorePatterns: ["/*", "!/src", "!/prisma"],
rules: {},
rules: {
"no-restricted-syntax": [
"error",
{
selector: "MemberExpression[type=MemberExpression][object.type=MemberExpression][object.object.type=Identifier][object.object.name=process][object.property.type=Identifier][object.property.name=env]",
message: "Don't use process.env directly in Stack's backend. Use getEnvVariable(...) or getNodeEnvironment() instead.",
},
],
},
};
6 changes: 2 additions & 4 deletions apps/backend/src/app/api/v1/contributors/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import * as yup from "yup";
import sharp from "sharp";
import { captureError } from "@stackframe/stack-shared/dist/utils/errors";
import { getNodeEnvironment } from "@stackframe/stack-shared/dist/utils/env";

let pngImagePromise: Promise<Uint8Array> | undefined;

Expand All @@ -18,7 +19,7 @@ export const GET = createSmartRouteHandler({
}).required(),
}),
handler: async () => {
if (process.env.NODE_ENV === "development" || !pngImagePromise) {
if (getNodeEnvironment() === "development" || !pngImagePromise) {
pngImagePromise = (async () => {
const ghPage = await fetch("https://github.com/stack-auth/stack");
const ghPageText = await ghPage.text();
Expand Down Expand Up @@ -77,9 +78,6 @@ export const GET = createSmartRouteHandler({
})();
pngImagePromise.catch((error) => {
captureError("contributors-image", error);
if (process.env.NODE_ENV === "development") {
pngImagePromise = undefined;
}
});
}

Expand Down
3 changes: 2 additions & 1 deletion apps/backend/src/lib/tokens.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { decryptJWT, encryptJWT } from '@stackframe/stack-shared/dist/utils/jwt'
import { KnownErrors } from '@stackframe/stack-shared';
import { prismaClient } from '@/prisma-client';
import { generateSecureRandomString } from '@stackframe/stack-shared/dist/utils/crypto';
import { getEnvVariable } from '@stackframe/stack-shared/dist/utils/env';

export const authorizationHeaderSchema = yup.string().matches(/^StackSession [^ ]+$/);

Expand Down Expand Up @@ -56,7 +57,7 @@ export async function encodeAccessToken({
projectId: string,
userId: string,
}) {
return await encryptJWT({ projectId, userId }, process.env.STACK_ACCESS_TOKEN_EXPIRATION_TIME || '1h');
return await encryptJWT({ projectId, userId }, getEnvVariable("STACK_ACCESS_TOKEN_EXPIRATION_TIME", "1h"));
}

export async function createAuthTokens({
Expand Down
3 changes: 2 additions & 1 deletion apps/backend/src/oauth/providers/facebook.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { TokenSet } from "openid-client";
import { OAuthBaseProvider } from "./base";
import { OAuthUserInfo, validateUserInfo } from "../utils";
import { getEnvVariable } from "@stackframe/stack-shared/dist/utils/env";

export class FacebookProvider extends OAuthBaseProvider {
constructor(options: {
Expand All @@ -11,7 +12,7 @@ export class FacebookProvider extends OAuthBaseProvider {
issuer: "https://www.facebook.com",
authorizationEndpoint: "https://facebook.com/v20.0/dialog/oauth/",
tokenEndpoint: "https://graph.facebook.com/v20.0/oauth/access_token",
redirectUri: process.env.NEXT_PUBLIC_STACK_URL + "/api/v1/auth/callback/facebook",
redirectUri: getEnvVariable("NEXT_PUBLIC_STACK_BACKEND_URL") + "/api/v1/auth/callback/facebook",
baseScope: "public_profile email",
...options
});
Expand Down
3 changes: 2 additions & 1 deletion apps/backend/src/oauth/providers/github.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { TokenSet } from "openid-client";
import { OAuthBaseProvider } from "./base";
import { OAuthUserInfo, validateUserInfo } from "../utils";
import { getEnvVariable } from "@stackframe/stack-shared/dist/utils/env";

export class GithubProvider extends OAuthBaseProvider {
constructor(options: {
Expand All @@ -12,7 +13,7 @@ export class GithubProvider extends OAuthBaseProvider {
authorizationEndpoint: "https://github.com/login/oauth/authorize",
tokenEndpoint: "https://github.com/login/oauth/access_token",
userinfoEndpoint: "https://api.github.com/user",
redirectUri: process.env.NEXT_PUBLIC_STACK_URL + "/api/v1/auth/callback/github",
redirectUri: getEnvVariable("NEXT_PUBLIC_STACK_BACKEND_URL") + "/api/v1/auth/callback/github",
baseScope: "user:email",
...options,
});
Expand Down
3 changes: 2 additions & 1 deletion apps/backend/src/oauth/providers/google.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { TokenSet } from "openid-client";
import { OAuthBaseProvider } from "./base";
import { OAuthUserInfo, validateUserInfo } from "../utils";
import { getEnvVariable } from "@stackframe/stack-shared/dist/utils/env";

export class GoogleProvider extends OAuthBaseProvider {
constructor(options: {
Expand All @@ -12,7 +13,7 @@ export class GoogleProvider extends OAuthBaseProvider {
authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
tokenEndpoint: "https://oauth2.googleapis.com/token",
userinfoEndpoint: "https://openidconnect.googleapis.com/v1/userinfo",
redirectUri: process.env.NEXT_PUBLIC_STACK_URL + "/api/v1/auth/callback/google",
redirectUri: getEnvVariable("NEXT_PUBLIC_STACK_BACKEND_URL") + "/api/v1/auth/callback/google",
baseScope: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
...options,
});
Expand Down
3 changes: 2 additions & 1 deletion apps/backend/src/oauth/providers/microsoft.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { TokenSet } from "openid-client";
import { OAuthBaseProvider } from "./base";
import { OAuthUserInfo, validateUserInfo } from "../utils";
import { getEnvVariable } from "@stackframe/stack-shared/dist/utils/env";

export class MicrosoftProvider extends OAuthBaseProvider {
constructor(options: {
Expand All @@ -11,7 +12,7 @@ export class MicrosoftProvider extends OAuthBaseProvider {
issuer: "https://login.microsoftonline.com",
authorizationEndpoint: "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize",
tokenEndpoint: "https://login.microsoftonline.com/consumers/oauth2/v2.0/token",
redirectUri: process.env.NEXT_PUBLIC_STACK_URL + "/api/v1/auth/callback/microsoft",
redirectUri: getEnvVariable("NEXT_PUBLIC_STACK_BACKEND_URL") + "/api/v1/auth/callback/microsoft",
baseScope: "User.Read",
...options,
});
Expand Down
3 changes: 2 additions & 1 deletion apps/backend/src/oauth/providers/spotify.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { TokenSet } from "openid-client";
import { OAuthBaseProvider } from "./base";
import { OAuthUserInfo, validateUserInfo } from "../utils";
import { getEnvVariable } from "@stackframe/stack-shared/dist/utils/env";

export class SpotifyProvider extends OAuthBaseProvider {
constructor(options: {
Expand All @@ -11,7 +12,7 @@ export class SpotifyProvider extends OAuthBaseProvider {
issuer: "https://accounts.spotify.com",
authorizationEndpoint: "https://accounts.spotify.com/authorize",
tokenEndpoint: "https://accounts.spotify.com/api/token",
redirectUri: process.env.NEXT_PUBLIC_STACK_URL + "/api/v1/auth/callback/spotify",
redirectUri: getEnvVariable("NEXT_PUBLIC_STACK_BACKEND_URL") + "/api/v1/auth/callback/spotify",
baseScope: "user-read-email user-read-private",
...options,
});
Expand Down
3 changes: 2 additions & 1 deletion apps/backend/src/prisma-client.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

import { PrismaClient } from '@prisma/client';
import { getNodeEnvironment } from '@stackframe/stack-shared/dist/utils/env';

// In dev mode, fast refresh causes us to recreate many Prisma clients, eventually overloading the database.
// Therefore, only create one Prisma client in dev mode.
Expand All @@ -8,7 +9,7 @@ const globalForPrisma = global as unknown as { prisma: PrismaClient };
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
export const prismaClient = globalForPrisma.prisma || new PrismaClient();

if (process.env.NODE_ENV !== 'production') {
if (getNodeEnvironment() !== 'production') {
globalForPrisma.prisma = prismaClient;
}

10 changes: 7 additions & 3 deletions packages/stack-shared/src/utils/env.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ export function isBrowserLike() {
}

/**
* Returns the environment variable with the given name, throwing an error if it's undefined or the empty string.
* Returns the environment variable with the given name, returning the default (if given) or throwing an error (otherwise) if it's undefined or the empty string.
*/
export function getEnvVariable(name: string): string {
export function getEnvVariable(name: string, defaultValue?: string | undefined): string {
if (isBrowserLike()) {
throw new Error(deindent`
Can't use getEnvVariable on the client because Next.js transpiles expressions of the kind process.env.XYZ at build-time on the client.
Expand All @@ -17,5 +17,9 @@ export function getEnvVariable(name: string): string {
`);
}

return (process.env[name] ?? throwErr(`Missing environment variable: ${name}`)) || throwErr(`Empty environment variable: ${name}`);
return ((process.env[name] || defaultValue) ?? throwErr(`Missing environment variable: ${name}`)) || (defaultValue ?? throwErr(`Empty environment variable: ${name}`));
}

export function getNodeEnvironment() {
return getEnvVariable("NODE_ENV", "");
}
3 changes: 2 additions & 1 deletion turbo.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"SENTRY_*",
"VERCEL_GIT_COMMIT_SHA",
"NEXT_PUBLIC_POSTHOG_*",
"POSTHOG_*"
"POSTHOG_*",
"NODE_ENV"
],
"tasks": {
"build": {
Expand Down

0 comments on commit fb825e6

Please sign in to comment.