puddlejumper26
puddlejumper26

Reputation: 33

How to read .env/.env.local file in Next.js (App Router)

I cannot read the API values in .env / .env.local file in next.js with latest App Router.

As far as I understand, the .env should be enabled under the hood in react.

I have tried many methods from here, but still failed.

Including installed dotenv and

const dotenv = require("dotenv");
const env = dotenv.config().parsed;

I tried to log out in

Here are the steps I tried

root file

.env

GOOGLE_CLIENT_ID='values'
GOOGLE_CLIENT_SECRET="values"

client side file

"use client";

useEffect(()=>{
   console.log(process.env.GOOGLE_CLIENT_ID)   ===> undefined
},[])

lib/session.ts

import { getServerSession } from "next-auth/next";
import { NextAuthOptions, User } from "next-auth";
import { AdapterUser } from "next-auth/adapters";
import GoogleProvider from "next-auth/providers/google";
import jsonwebtoken from "jsonwebtoken";
import { JWT } from "next-auth/jwt";
import { SessionInterface } from "@/common.types";

export const authOptions: NextAuthOptions = {
  providers: [
    GoogleProvider({
      clientId:
        process.env.GOOGLE_CLIENT_ID|| "",  ===>  could not obtain value
      clientSecret: process.env.GOOGLE_CLIENT_SECRET || "",
    }),
  ],

=========

So i checked this page from NextJs https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables,

and reset .env to .env.local

still undefined

=========

I installed dotenv

client side file

"use client";

const dotenv = require("dotenv");
const env = dotenv.config().parsed; 

useEffect(()=>{
   console.log(process.env.GOOGLE_CLIENT_ID)   ===> undefined
},[])

Upvotes: 0

Views: 1499

Answers (1)

CodeBird
CodeBird

Reputation: 502

You should be able to access the env variables using process.env.<VARIABLE_NAME> in NextJS.

If that didn't work for you, please share what all you tried and what the result was.

Upvotes: 0

Related Questions