Next.js Discord

Discord Forum

What's better way to call .env variable to a TS file?

Unanswered
Tomistoma posted this in #help-forum
Open in Discord
TomistomaOP
It's my first time using Next.js with TypeScript and I'm wondering if there's a better way to pass .env variables to a TypeScript file.

here's my code at the moment

import { Client, Databases } from 'appwrite';

export const client = new Client();
export const databases = new Databases(client);

client
  .setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT as string)
  .setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID as string);


as you can see, to fix my ts error, Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. I have to add as string after my env variable. Just wondering if there is a better way to do this. without installing package?

2 Replies

Most people just create a env.ts file and export a const object name env containing the environment variables and asserting it to a string in there, in order to get both autocomplete for env variables and avoid TypeErrors.

I wanted to go a step further and use Zod to validate the envs were there and throw an error if they weren't, but, unfortunately that doesn't work when you have server-only envs.
TomistomaOP
thank you @Plague will look into this.