PeanutButterSolution
PeanutButterSolution

Reputation: 53

How do I get access to a token in .env to fetch data in Next.js?

I am creating an app (Next.js v9.4.2 / React.js) that requires x-auth tokens to be sent to the backend.

I have a .env file where the token is defined; a next.config.js file where I listed the token under env: {}; and a .getInitialProps fn where I am trying to use the token via process.env.TOKEN (see below).

The fetch fails (returns "Internal Server Error") when I reference process.env.TOKEN, but NOT when I hardcode the token as a string:

.env

TOKEN=12345-6789

next.config.js

const withSass = require('@zeit/next-sass')
const withCSS = require("@zeit/next-css")
require('dotenv').config()

module.exports = withCSS(withSass({
    env: {
        TOKEN: process.env.TOKEN
    }
}));

Component

Page.getInitialProps = async function (context) {
    const id = context.query.id ? context.query.id : {}

    const res = await fetch(`https://url/${id}/`, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'x-auth-token': `${process.env.TOKEN}`,
        }
    })
    let raw = await res.json();

    return {
        data: raw
    }
}

Upvotes: 1

Views: 8247

Answers (2)

Mahesh Auti
Mahesh Auti

Reputation: 86

depends on which NextJs version you are using. latest nextjs version has built-in support for environment variables. https://nextjs.org/docs/basic-features/environment-variables

if you are using older version then you can configure next.config.js like this:

require("dotenv").config();

module.exports = withImages(withCSS(withSass({
        webpack: config => {
            /**
             * Returns environment variables as an object
             */
            const env = Object.keys(process.env).reduce((acc, curr) => {
              acc[`process.env.${curr}`] = JSON.stringify(process.env[curr]);

              return acc;
            }, {});
            // Fixes npm packages that depend on `fs` module
            config.node = {
              fs: 'empty'
            };

             /** Allows you to create global constants which can be configured
            * at compile time, which in our case is our environment variables
            */
            config.plugins.push(new webpack.DefinePlugin(env));

            return config;
          },
    })));

Upvotes: 1

Sanket Phansekar
Sanket Phansekar

Reputation: 741

Use serverRuntimeConfig parameter to access the env variables on server side.

Need to do like this:

next.config.js

const withSass = require('@zeit/next-sass')
const withCSS = require("@zeit/next-css")
require('dotenv').config()

module.exports = withCSS(withSass({
    serverRuntimeConfig: {
        TOKEN: process.env.TOKEN 
    }
}));

Refer: https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration

Upvotes: 0

Related Questions