Where I can do some initialisation of app like to init database connection? #16271
Replies: 6 comments 3 replies
-
There is no singleton like that available with Next applications. Instead you initialize the database connection as you need it. For example the MongoDB example shows this off: next.js/examples/with-mongodb/pages/index.js Lines 225 to 233 in cdff5df |
Beta Was this translation helpful? Give feedback.
-
I managed to do this with a singleton to manage connections with mongodb. (I haven't test it in production)
Then I have a a file for the query
Then from my page I use that query
Logs say it only connects once and reuses connection among several requests:
|
Beta Was this translation helpful? Give feedback.
-
Imho this reply is not clear enough, I answer only to help others in my same position... I found an example util in a mongodb example project, so the code is not written by me. After creating this file, for example under utils
You then can import it
Then you can go ahead with the example of @jamesmosier This is the project example that I have took the file from https://github.com/lucasmmaidana/nextbnb/blob/main/pages/index.js |
Beta Was this translation helpful? Give feedback.
-
hi |
Beta Was this translation helpful? Give feedback.
-
This in theory is fine. But I still see more connections getting created constantly. Even when using some sort of caching using LRU-cache or just as a global variable map of database names to connections. i think that has to do with how functions are run in a serverless environment. Any way around this? |
Beta Was this translation helpful? Give feedback.
-
Ive managed this by putting this in the root layout |
Beta Was this translation helpful? Give feedback.
-
Hi, I want to use typescript like db.ts to initialize the database connection.
I can not write it in next.config.js, since I using typeORM it is base on typescript not javascript to connection database.
Where or which file can do it to make sure the database only connected once during the booting app process.
any variable can share as the global variable during the running of app? where to set them.
Beta Was this translation helpful? Give feedback.
All reactions