next-runtime-env usage in Documenso source code

In this article, we analyse next-runtime-env usage in Documenso source code and what is next-runtime-env.

What is next-runtime-env?

Using next-runtime-env, you can effortlessly populate your environment at runtime, not just at build time. Read more about next-runtime-env.

next-runtime-env dynamically injects environment variables into your Next.js application at runtime. This approach adheres to the “build once, deploy many” principle, allowing the same build to be used across various environments without rebuilds.

Quick start

  1. Add PublicEnvScript in the root layout.tsx.
// app/layout.tsx
import { PublicEnvScript } from 'next-runtime-env';
export default function RootLayout({ children }) {
 return (
   <html lang="en">
     <head>
       <PublicEnvScript />
     </head>
     <body>
       {children}
     </body>
   </html>
 );
}

The PublicEnvScript component automatically exposes all environment variables prefixed with NEXT_PUBLIC_ to the browser

2. Access your environment variables.

// app/client-page.tsx
'use client';

import { env } from 'next-runtime-env';

export default function SomePage() {
 const NEXT_PUBLIC_FOO = env('NEXT_PUBLIC_FOO');
 return <main>NEXT_PUBLIC_FOO: {NEXT_PUBLIC_FOO}</main>;
}

next-runtime-env usage in Documenso

Based on the documentation, the first step was to add PublicEnvScript in the root layout. You will find this in app/layout.tsx.

<head>
 <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
 <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
 <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
 <link rel="manifest" href="/site.webmanifest" />
 {IS_APP_WEB_I18N_ENABLED && <meta name="google" content="notranslate" />}
 <PublicEnvScript />
</head>

And the next step was accesing env variables. One such example is found in put-file.ts

export const putFile = async (file: File) => {

  const NEXT_PUBLIC_UPLOAD_TRANSPORT = env('NEXT_PUBLIC_UPLOAD_TRANSPORT');

  return await match(NEXT_PUBLIC_UPLOAD_TRANSPORT)
   .with('s3', async () => putFileInS3(file))
   .otherwise(async () => putFileInDatabase(file));
};

Here env is used to access an environment variable called NEXT_PUBLIC_UPLOAD_TRANSPORT. This way, when you change your env variables, you don’t have to rebuild your Next.js application.

About us:

At Thinkthroo, we study large open source projects and provide architectural guides. We have developed reusable Components, built with tailwind, that you can use in your project.

We offer Next.js, React and Node development services.

Book a meeting with us to discuss your project.

References:

  1. https://github.com/documenso/documenso/blob/main/packages/lib/universal/upload/put-file.ts#L2

  2. https://www.npmjs.com/package/next-runtime-env