Xata issues with environment variables in NestJS
I have a simple NestJS app, generated through their cli, and have attempted to add Xata to the project to use as my database. I've ran the
xata init
command, and everything generated correctly and my environment variables were added to my .env
file. However, where I try to run my app with pnpm start:dev
(a precreated script) I get this error:
This is my KeyCache.ts
file:
My environment variables are working fine as in the root file (main.ts
) I have the following code:
and the appropriate variable is outputted near the start of the logs (before the errors).
Does anyone know what might be causing this error? Could it be the way in which files are loaded in NestJS, meaning that the KeyCache file that requires xata be loaded before environment variables are set/available to the app?
Thanks in advance :)3 Replies
Hi, indeed it looks like the Xata client cannot get the API key env variable during instantiation. Maybe it has to do with the Config Module? https://docs.nestjs.com/techniques/configuration#getting-started
To work around this you can try importing the XataClient and pass the key and other parameters to it explicitly: https://xata.io/docs/sdk/typescript/overview#manually-passing-the-apikey
We've found this approach necessary for other frameworks as well such as SvelteKit, which has a particular way of using env variables (see the XataClient config in this example https://xata.io/docs/getting-started/sveltekit#query-and-list-the-posts)
This didn't seem to work
In my
app.module.ts
file, as per the docs, I checked that my code matched the doc's code (which is did)
as well as manually passing the api key, changing this
to this
I'm still confused how this error is even occuring at that point, because chronologically in the logs it goes:
I tried the sample nestJS app https://docs.nestjs.com/#installation and set it to read from Xata with no issues. I made changes to app.service.ts and app.controller.ts to return Promise.
The Xata client picks up the Xata API key from .env and returns query results. see the recording.
Can you try the same on the sample nestJS app and see if that works for you? I suspect some caching or build issue, maybe try on a fresh project?
Documentation | NestJS - A progressive Node.js framework
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).