1

I'm implementing next-auth into my nextjs-13 app, but when I tried to use .env variables in the [...nextauth]/route.ts it shows error:

Type 'string | undefined' is not assignable to type 'string'.

error is shown in the image

Project details

Package Name Package version
Next JS (with app route and src/ directory) 13.4.4
Type script 5.1.3
next-auth 4.22.1

.env file

GOOGLE_CLIENT_ID=my-Client-Id
GOOGLE_CLIENT_SECRET=my-Client-Secret
  • TypeScript doesn't know what an .env file is (and even if it did it can't know whether you loaded it or not). If you use an environment variable it can't know if it's been set or not at compile time – apokryfos Jun 09 '23 at 06:17

1 Answers1

0

Option 1: Casting

The simple solution is to just cast the environment variables to strings like below. This will work fine if you know your environment variables are defined. However you will get errors if you every in the future forget to set them.

GoogleProvider({
  clientId: process.env.GOOGLE_CLIENT_ID as string,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
})

Option 2: Type narrowing

You can make sure that your env variables are defined before accessing them. This can get very repetitive though. Typescript will now know that are not undefined are this code block. You have the same problem as in option 1 though pretty much.

if (
  process.env.GOOGLE_CLIENT_ID === undefined ||
  process.env.GOOGLE_CLIENT_SECRET == undefined
) {
  throw new Error('Invalid env vars');
}

Option 3: Typed env vars

This is in my opinion the best option. I can strongly recommend the package t3-env. Then you will have access to type safe environment variables.

Felix Eklöf
  • 3,253
  • 2
  • 10
  • 27