Next.js Discord

Discord Forum

Where is the starting point, something equivalent to a main.ts file in other frameworks?

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
Basically I'm not sure where to initialize stuff like my database connector, should I do this in the root layout.tsx? Feels like a bad practice to me

7 Replies

@Cape lion Basically I'm not sure where to initialize stuff like my database connector, should I do this in the root layout.tsx? Feels like a bad practice to me
I would create a dedicated file for it. For example like db.ts and then export a singleton from there. If there is a DB instance: use it. If there is none, initialize a new one. Like that you should be pretty safe
^ this way if you import the same exported instance it should only be one db connection, even if used in 50 different files
@Cape lionsolved?
Cape lionOP
Ok, but in what file do I import the db.ts file if I want to initialize the database on app start? @B33fb0n3
And its connection is shared
And if you use top level import, iirc it should also connect on app start (maybe not serverless like vercel unless that route uses it)