Skip to content

Commit

Permalink
feat: runtime env variables with next-runtime-env
Browse files Browse the repository at this point in the history
  • Loading branch information
manolo-battista committed Sep 5, 2024
1 parent 5286f23 commit a25e58f
Show file tree
Hide file tree
Showing 16 changed files with 4,026 additions and 3,148 deletions.
8 changes: 4 additions & 4 deletions .env.development
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
NEXT_PUBLIC_ARKE_SERVER_URL=http://0.0.0.0:4000
NEXT_MULTIPROJECT=true
NEXTAUTH_URL=http://localhost:3100/api/auth
NEXTAUTH_SECRET=your_secret
NEXT_PUBLIC_ARKE_SERVER_URL="http://0.0.0.0:4000"
NEXT_PUBLIC_ARKE_PROJECT=""
NEXT_PUBLIC_MULTIPROJECT="true"
NEXTAUTH_URL="http://localhost:3100/api/auth"
NEXTAUTH_SECRET="your_secret"
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"plugins": ["prettier"],
"extends": ["next/core-web-vitals", "plugin:prettier/recommended"],
"rules": {
"react-hooks/exhaustive-deps": "off"
"react-hooks/exhaustive-deps": "off",
"@next/next/no-sync-scripts": "off"
}
}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,6 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts

# Runtime env
/public/__ENV.js
28 changes: 7 additions & 21 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
FROM node:18-alpine AS base

ARG ARKE_SERVER_SSR_URL="http://host.docker.internal:4000"
ARG ARKE_SERVER_URL="http://0.0.0.0:4000"
ARG NEXTAUTH_URL="http://localhost:3100/api/auth"
ARG PROJECT_ID

# Install dependencies only when needed
FROM base AS deps
RUN apk add --no-cache libc6-compat
Expand All @@ -27,17 +22,6 @@ WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Build .env file
RUN echo NEXTAUTH_SECRET=\" | tr -d '\n' > .env.production \
&& openssl rand -base64 32 | tr -d '\n' >> .env.production \
&& echo \" >> .env.production \
&& echo NEXT_PUBLIC_ARKE_SERVER_URL= | tr -d '\n' >> .env.production \
&& echo $ARKE_SERVER_URL >> .env.production \
&& echo NEXT_PUBLIC_ARKE_SERVER_SSR_URL= | tr -d '\n' >> .env.production \
&& echo $ARKE_SERVER_SSR_URL >> .env.production \
&& echo NEXTAUTH_URL= | tr -d '\n' >> .env.production \
&& echo $NEXTAUTH_URL >> .env.production

RUN yarn build

# Production image, copy all the files and run next
Expand All @@ -50,14 +34,16 @@ RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public
COPY --from=builder /app/entrypoint.sh ./entrypoint.sh

COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3100
# Create the __ENV.js file dynamically
RUN apk add --no-cache bash
RUN chmod +x entrypoint.sh

ENV PORT 3100
EXPOSE 3000
ENV PORT 3000

CMD ["node", "server.js"]
ENTRYPOINT ["/app/entrypoint.sh"]
13 changes: 3 additions & 10 deletions arke/getClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,17 @@
* limitations under the License.
*/

import { Client, HTTPStatusCode, TToken } from "@arkejs/client";
import { Client, TToken } from "@arkejs/client";
import { GetServerSidePropsContext } from "next";
import { getSession } from "next-auth/react";
import { getToken } from "next-auth/jwt";
import { getCookie } from "cookies-next";
import { getCookieName } from "@/utils/auth";
import { NextParsedUrlQuery } from "next/dist/server/request-meta";
import { redirect } from "next/navigation";
import { env } from "next-runtime-env";

const getServerUrl = () => {
if (
typeof window == "undefined" &&
process.env.NEXT_PUBLIC_ARKE_SERVER_SSR_URL
) {
return process.env.NEXT_PUBLIC_ARKE_SERVER_SSR_URL;
}

return process.env.NEXT_PUBLIC_ARKE_SERVER_URL;
return env("NEXT_PUBLIC_ARKE_SERVER_URL");
};

const getProjectId = (context?: {
Expand Down
2 changes: 1 addition & 1 deletion components/AppFormConfigProvider/AppFormConfigProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export default function AppFormConfigProvider(props: { children: ReactNode }) {
onChange={(value) => field.onChange(JSON.parse(value))}
/>
),
dynamic: ({ field }) => (
dynamic: ({ field }: any) => (
<Json
label={field.label}
value={JSON.stringify(field.value)}
Expand Down
18 changes: 18 additions & 0 deletions entrypoint.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#!/bin/bash

# Create __ENV.js file in the public directory
echo "window.__ENV = {" > ./public/__ENV.js

# Loop through all environment variables
for var in $(env | grep '^NEXT_PUBLIC_' | cut -d= -f1); do
# Extract the variable name and value
value=$(printenv "$var")
# Format and append to __ENV.js
echo " $var: \"${value}\"," >> ./public/__ENV.js
done

# Close the JSON object in __ENV.js
echo "};" >> ./public/__ENV.js

# Start the server
node server.js
6 changes: 6 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@
* limitations under the License.
*/

const { configureRuntimeEnv } = require("next-runtime-env/build/configure");
const { makeEnvPublic } = require("next-runtime-env/build/make-env-public");

/* Runtime ENV variables */
configureRuntimeEnv();

/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"cookies-next": "^2.1.1",
"next": "13.2.4",
"next-auth": "^4.22.1",
"next-runtime-env": "^1.7.4",
"prismjs": "^1.29.0",
"react": "18.2.0",
"react-dom": "18.2.0",
Expand Down
2 changes: 1 addition & 1 deletion pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import "@/styles/prism.css";
import type { AppProps } from "next/app";
import { Inter } from "next/font/google";
import { SessionProvider } from "next-auth/react";
import { NextPage } from "next";
import { GetStaticProps, NextPage } from "next";
import AppFormConfigProvider from "@/components/AppFormConfigProvider/AppFormConfigProvider";
import dynamic from "next/dynamic";
import AppTableConfigProvider from "@/components/Table/AppTableConfigProvider";
Expand Down
3 changes: 2 additions & 1 deletion pages/_document.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@
* limitations under the License.
*/

import { Html, Head, Main, NextScript } from "next/document";
import { Html, Main, Head, NextScript } from "next/document";

export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<script src="/__ENV.js" />
<Main />
<NextScript />
</body>
Expand Down
7 changes: 4 additions & 3 deletions pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { Client, HTTPStatusCode } from "@arkejs/client";
import { NextApiRequest, NextApiResponse } from "next";
import { JWT } from "next-auth/jwt";
import { getClient } from "@/arke/getClient";
import { env } from "next-runtime-env";

const refreshToken = async (client: Client, token: JWT): Promise<JWT> => {
return new Promise((resolve) =>
Expand Down Expand Up @@ -60,7 +61,7 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {
"credentials",
{
headers: {
"Arke-Project-Key": process.env.NEXT_PUBLIC_ARKE_PROJECT,
"Arke-Project-Key": env("NEXT_PUBLIC_ARKE_PROJECT"),
},
}
);
Expand All @@ -75,7 +76,7 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {
},
}),
];
const useSecureCookies = process.env.NEXTAUTH_URL?.startsWith("https://");
const useSecureCookies = env("NEXTAUTH_URL")?.startsWith("https://");
const cookiePrefix = useSecureCookies ? "__Secure-" : "";

return await NextAuth(req, res, {
Expand Down Expand Up @@ -119,7 +120,7 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {
},
},
providers,
secret: process.env.NEXTAUTH_SECRET,
secret: env("NEXTAUTH_SECRET"),
pages: {
signIn: "/login",
signOut: "/logout",
Expand Down
3 changes: 2 additions & 1 deletion pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import { isMultiProjectConsole } from "@/utils/system";
import serverErrorRedirect from "@/server/serverErrorRedirect";
import { getSession } from "next-auth/react";
import { User } from "next-auth";
import { env } from "next-runtime-env";

export default function Home(props: { projects: TProject[]; user: User }) {
const client = useClient();
Expand Down Expand Up @@ -173,7 +174,7 @@ export const getServerSideProps: GetServerSideProps = withAuth(
} else {
return {
redirect: {
destination: `/${process.env.NEXT_PUBLIC_ARKE_PROJECT}`,
destination: `/${env("NEXT_PUBLIC_ARKE_PROJECT")}`,
permanent: false,
},
};
Expand Down
Loading

0 comments on commit a25e58f

Please sign in to comment.