Armen Sanoyan
Armen Sanoyan

Reputation: 2032

Get env variables inside _middleware Next.js

Inside my nextjs project I have variables added in both .env and next.conf.js files. Inside next.conf.js file it looks like this

module.exports = {
  env: {
    NEXT_PUBLIC_JWT_SECRET: "...",
  },
  publicRuntimeConfig: {
    NEXT_PUBLIC_JWT_SECRET: "...",
    API_JWT_SECRET: process.env.API_JWT_SECRET,
  },
  serverRuntimeConfig: {
    // Will only be available on the server side
    NEXT_PUBLIC_JWT_SECRET: "...",
    secondSecret: process.env.JWT_SECRET, // Pass through env variables
  },
};

I have tried all this ways to get the secret ket in my _middleware file, but none of them worked. From this github issue I assume that there is a way to do that. So could you please show me the correct way to get secret ket inside _middleware?

Upvotes: 1

Views: 4285

Answers (1)

Armen Sanoyan
Armen Sanoyan

Reputation: 2032

As hugefunwoo says

Next.js will replace process.env.customKey with 'my-value' at build time. Trying to destructure process.env variables won't work due to the nature of webpack DefinePlugin.

const { JWT_SECRET } = process.env 

This will return undefind so I had to replace it by

const JWT_SECRET = process.env.JWT_SECRET

Upvotes: 1

Related Questions