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

3 messages · Page 1 of 1 (latest)

strange fog
#

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?

wooden rapidsBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

dense phoenix
#

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.