How to Work with Environment Variables in Next.js
While working with Next.js, sometimes, I want to know where my code runs (node, browser), what environment my code runs on (development, production, test), and how to get the environment variables. Yes! In this article, I will show you how I can do it.
Create the Environment Service
To work with Environment Variables in Next.js, I will create a module named env.service.ts in the src/shared folder. So I can use this module for both frontend and backend.
The content of the env.service.ts file will be like this.
// src/shared/services/env.service.ts
export namespace EnvService {
export function get(key: string) {
return process.env[key]!;
}
export function isNode() {
return !process.browser;
}
export function isBrowser() {
return process.browser;
}
export function isDev() {
return process.env.NODE_ENV === 'development';
}
export function isProd() {
return process.env.NODE_ENV === 'production';
}
export function isTest() {
return process.env.NODE_ENV === 'test';
}
}
Use the Environment Service
First of all, in the root folder, I will create a file named .env with the content below. This .env file will store my environment variables.
NEXT_PUBLIC_VARIABLE=Next Full Stack
And, to use the env.service.ts module, I will replace the src/pages/index.tsx file content with these lines.
// src/pages/index.tsx
import { EnvService } from '@shared/services/env.service';
export default function Page() {
console.log('isBrowser:', EnvService.isBrowser());
console.log('isNode:', EnvService.isNode());
console.log('isProd:', EnvService.isProd());
console.log('isDev:', EnvService.isDev());
console.log('isTest:', EnvService.isTest());
console.log('get:', EnvService.get('NEXT_PUBLIC_VARIABLE'));
return <h1>Hello World!</h1>;
}
Now, restart the server by re-running yarn dev and go to http://localhost:3000 to see the result.
Demo: https://next-full-stack-git-issue-2.maxvien.vercel.app/
Source Code
You can find the source code of this tutorial in this commit: https://github.com/VienDinhCom/esmate/tree/1dd2dd1169f6cf63e2ec152151416f6c3ec66c93