#Environment variables for api routes

1 messages · Page 1 of 1 (latest)

sharp void
#

Does or should an environment variable that is going to be used in an API route have to be prepended with NEXT_PUBLIC?

vapid tulipBOT
#

Hi @sharp void. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

No, environment variables that are going to be used in an API route do not need to be prepended with NEXT_PUBLIC_. The NEXT_PUBLIC_ prefix is used to expose environment variables on the client-side. For server-side code such as API routes, you can directly use environment variables without this prefix.

You can use process.env to access environment variables for both next dev and next build. For example, if you have a .env.local file with the following content:

DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword

You can access these variables in your API route like this:

export async function GET() {
 const db = await myDB.connect({
 host: process.env.DB_HOST,
 username: process.env.DB_USER,
 password: process.env.DB_PASS,
 })
 // ...
}

Remember, if you are using a /src folder, Next.js will load the .env files only from the parent folder and not from the /src folder.

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: