I'm trying to manage the session in a simple way: loading the data from the DB when a request arrive and save the data into the DB when the request finish. But I'm facing two main problems: 1. Next.js complains when I try to access the DB (sqlite) from a middleware because reading from filesystem is not supported by the Edge runtime; 2. I have no idea of when the request terminates and I'm ready to store the data into the DB. I don't want to make a query every time the session has changed but only once at the end of the request lifecycle. I keep reading the Next.js docs to find an answer but it seems like it isn't there at all. I know I can store the whole session into an encrypted cookie or that I should avoid heavy tasks inside middlewares but that's my actual need nonethless. Is there a way a can achieve this goal? Thanks in advance for your help and time.
#Hello, how can I learn more about request lifecycle and database session management?
16 messages · Page 1 of 1 (latest)
🔎 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)
ChatGPT gave me this solutions:
// middleware.js
export default function sessionMiddleware(handler) {
return async (req, res) => {
const sessionData = await loadSessionFromDatabase(req);
req.session = sessionData;
const response = await handler(req, res);
await saveSessionToDatabase(req.session);
return response;
};
}
// api/route.js
import sessionMiddleware from '../../middleware';
export default sessionMiddleware(async (req, res) => {
});
I have not tested it yet but it looks reasonable though I suspect some of the features are not documented or not much clear to grasp by reading the official docs.
For knowing when the request finishes you can't
at least in a canonical serverless setup
when using a custom server you have more control https://nextjs.org/docs/pages/building-your-application/configuring/custom-server
you might want to take a look at telemetry systems tailored for Next
I am not sure how they work because, since the router have total control on sending back the HTTP request, you don't really have a way to figure when the response actually happens
actually maybe they work by patching HTTP sending method
like they alter the underlying "res.send" in Node.js
to detect when it happens
it's worth digging
For the middleware thing yeah tha's a limitation of middlewares, they can't run on the Node.js runtime and have no Node.js equivalent
you might need to use an edge friendly solution like Upstash, difficult to tell more precisely as it depends on your exact situation