← coderrocketfuel.com

Add Environment Variables To A Next.js Application

Using environment variables is a great way to configure different parts of your Next.js application.

When you use source control software and/or deploy your application to production, you'll want to exclude certain credentials or variable values from being visible when taking those actions.

For instance, if you push your code to GitHub (or GitLab), you can add a .env declaration to your .gitignore file to exclude your credentials from being pushed with your code. This process will greatly limit the chance of your credentials being accidentally revealed to others by controlling what environments they show up in (i.e. only on your local development or production server machines).

You can add environment variables to your Next.js application by creating a env configuration object in your next.config.js file.

If you don't already have a next.config.js file, create one in the root of your Next.js application directory:

touch next.config.js

And add this code to the file:

module.exports = {
  env: {
    key: "value"
  }
}

Now you will be able to access the key variable anywhere in your Next.js application code using process.env.key.

For example, here's what that would look like in a React page:

import { Component } from "react"

export default class extends Component {
  render () {
    return (
      <p>Here is the value for the key environment variable: {process.env.key}</p>
    )
  }
}

That code will display the environment variable in the page.

If your next.config.js file contains sensitive information, you'll want to include the file in the .gitignore configuration file for your application:

next.config.js

This will stop Git from including the next.config.js file when you push code to a remote repository on GitHub or GitLab.

Thanks for reading and happy coding!