How to set up environment variables in Next.js



Image not found!!

In Next.js, you can set up environment variables to manage configuration settings for your application. Here's how you can set up environment variables in a Next.js project:

1. Create an .env file:

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

plaintext
NEXT_PUBLIC_API_URL=https://api.example.com SECRET_KEY=mysecretkey

2. Accessing Environment Variables in your Next.js code:

Next.js automatically loads environment variables from the .env file into process.env during the build process. You can access these variables in your code using process.env.

For example, in a Next.js component or page:

jsx
// pages/index.js const Home = () => { const apiUrl = process.env.NEXT_PUBLIC_API_URL; const secretKey = process.env.SECRET_KEY; return ( <div> <p>API URL: {apiUrl}</p> <p>Secret Key: {secretKey}</p> </div> ); }; export default Home;

3. Use Environment Variables in Next.js configuration files:

You can also use environment variables in Next.js configuration files, such as next.config.js. For example:

javascript
// next.config.js module.exports = { env: { API_URL: process.env.NEXT_PUBLIC_API_URL, SECRET_KEY: process.env.SECRET_KEY, }, };

Now, you can access these variables in your application using process.env.API_URL and process.env.SECRET_KEY.

4. Restart the development server:

After adding or updating environment variables, you need to restart the development server for the changes to take effect.

Important Notes:

  • Variables that start with NEXT_PUBLIC_ will be embedded in the client-side JavaScript. This is useful for values that need to be available on the client side.
  • Variables without the NEXT_PUBLIC_ prefix are only accessible on the server side.

Make sure not to share sensitive information like API keys directly in your code or repositories. Use environment variables to keep such information secure. Also, consider using a tool like dotenv to manage environment variables for different environments (development, production, etc.).