Search code examples
next.jsdotenv

nextJS how to load an environment variable properly


I am used to React and recently moved to NextJs, but facing a weird scenario. Having this Demo component rendered in a demo page;

import React from 'react';

import { Hello, Header } from './demo.styled';

export const Demo = () => {

  const name = process.env.userName || 'world';
  console.log("env vars userName v2: ", name)
  // env vars userName v2:  John Doe

  return (
    <Header>
      <Hello>Hello {name}!</Hello>
    </Header>
  );
};

I am having a .env file where the userName is John Doe, as you can see below the console log is the output, and it is well loaded.

But when my page is loaded, I get.

Hello world!

My project is recent, I am using

"next": "^12.1.4", "react": "17", "react-dom": "17",

And, my page is very simplistic, all it does is render the demo component.

Update

The logs set above are in server side, but in the client side, I have this message: next-dev.js?3515:25 Warning: Text content did not match. Server: "Jhon Doe" Client: "world"

What I understand is that my .env file is only on the server side, So how could I have these information on the client side too.


Solution

  • According to this document

    By default environment variables are only available in the Node.js environment, meaning they won't be exposed to the browser.

    As for your case, process.env.userName is only compiled during build-time and is available on the server-side merely.

    If you want to have it on the client-side, you need to have the prefix for your config NEXT_PUBLIC_userName (but following the name convention, I'd suggest you modify it to NEXT_PUBLIC_USERNAME)

    NEXT_PUBLIC_USERNAME=Jhon Doe
    

    And then you can change your code to

    const name = process.env.NEXT_PUBLIC_USERNAME || 'world';
    

    If you want to expose that userName on the client-side explicitly. You can update your next.config.js like below

    Your original env

    userName=Jhon Doe
    

    next.config.js

    module.exports = {
      //add other configs here too
      env: {
        userName: process.env.userName,
      },
    }
    

    With the 2nd solution, you don't need to modify your environment variables.