Next js environment variables

To use environment variables in a Next.js application, you can follow the steps outlined below:

Step 1: Create a .env file

Create a file named .env in the root directory of your Next.js project. This file will store your environment variables.

Step 2: Define the environment variables

Inside the .env file, define your environment variables using the KEY=VALUE syntax. For example, if you want to define a variable named API_URL with the value https://example.com/api, you would write API_URL=https://example.com/api in the .env file.

Step 3: Access the environment variables

In your Next.js code, you can access the environment variables using the process.env object. For example, if you defined the API_URL variable in the previous step, you can access it in your code using process.env.API_URL.

Step 4: Restart the development server

After defining the environment variables, you need to restart the Next.js development server for the changes to take effect. Stop the server if it's already running, and then start it again.

Step 5: Use the environment variables

You can now use the environment variables in your Next.js application. For example, if you want to use the API_URL variable from the previous steps, you can use it in your code like this: const apiUrl = process.env.API_URL.

That's it! You have now set up and accessed environment variables in your Next.js application. Remember to keep your .env file secure and avoid committing it to version control systems.