DEV Community

Cover image for How do you set up .env variables in your NextJS project ?
Kamal Nayan
Kamal Nayan

Posted on

How do you set up .env variables in your NextJS project ?

  1. First, ensure that the .env file is located in the root directory of your Next.js project.

  2. Make sure you have installed the required dependencies. You can use the dotenv package to load environment variables from the .env file. Run the following command to install it:

npm install dotenv
Enter fullscreen mode Exit fullscreen mode
  1. Create a file named next.config.js in the root directory of your project if it doesn't exist already. In that file, add the following code
require('dotenv').config();

module.exports = {
  env: {
    INFURA_IPFS_ID: process.env.INFURA_IPFS_ID,
  },
};
Enter fullscreen mode Exit fullscreen mode

This configuration will load the INFURA_IPFS_ID environment variable from the .env file and make it accessible in your Next.js app.

congratulations now you are good to go πŸš€

Image description

After following these steps, you should be able to access the INFURA_IPFS_ID variable using process.env.INFURA_IPFS_ID in your code, just like you are doing with the projectId variable.

Top comments (3)

Collapse
 
dotenv profile image
Dotenv

Check out .env.vault files as well. They have some security advantages over .env files. dev.to/dotenv/what-is-a-envvault-f...

Collapse
 
arisunarya profile image
Ari Sunarya

NextJs has runtime config, you can save private variable that can only accessed on the server-side, and you don't have to rebuild the project each time you change the variables

Collapse
 
kamalthedev profile image
Kamal Nayan

Good point made here @arisunarya