Best practises for loading environment variable in NextJS application
Deepak Kumar
Posted on March 13, 2023
How to load environment variables in a NextJS application ?
- First, create a new
.env
file in the root directory of your Next.js application. Add the environment variables you want to use in your application in the formatENV_VARIABLE_NAME=env_value
.
For example:
API_URL=https://example.com/api
API_KEY=abc123
- Next, please install the
dotenv
npm package dependency:
npm install --save-dev dotenv
- Now, in your Next.js application, create a new file named
next.config.js
in the root directory. This file will be used to load the environment variables from the.env
file.
const dotenv = require('dotenv');
dotenv.config();
module.exports = {
// Your Next.js configuration
};
- Now you can use the environment variables in your nextjs project. For example, to access the
API_URL
environment variable:
const apiUrl = process.env.API_URL;
console.log(apiUrl); // prints https://example.com/api
For more approach on how to load env file in nextjs application, you can refer this page - Link
Things to keep in mind when working with env files.
- You should never commit your
.env
file to git. Env secrets generally contains sensitive information such as API keys and passwords, database secrets. - You should add it to your
.gitignore
file to prevent it from being committed.
Here are the best practices you can consider for setting env secrets for your application :
-
Use a secure method to store your secrets:
- Avoid storing your secrets in plain text files or hardcoding them in your code. Instead, use a secure method such as environment variables, key vaults, or configuration files.
-
Limit access to your secrets
- Restrict access to your secrets to only those who need them. Use access controls and permissions to ensure that only authorized users can access your secrets.
-
Avoid storing sensitive data in plain text
- If you need to store sensitive data such as passwords or API keys, encrypt them before storing them in your secrets store.
-
Rotate your secrets regularly:
- Regularly rotating your secrets (e.g. passwords, api secret keys) helps to prevent unauthorised access and improve security.
- Set up automated processes to rotate your secrets at regular intervals.
-
Use strong, complex passwords:
- When creating passwords for your secrets, use strong, complex passwords that are difficult to guess.
- Use a password manager to generate and store passwords securely.
-
Use a version control system:
- You can use a version control system to manage changes to your secrets, and keep a record of who made changes and when.
💖 💪 🙅 🚩
Deepak Kumar
Posted on March 13, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev How Single Page Applications (SPAs) Can Boost Visitor-to-Customer Conversion Rates
November 10, 2024