Next.js Discord

Discord Forum

Hello, how can I learn more about request lifecycle and database session management?

Unanswered
Chausie posted this in #help-forum
Open in Discord
ChausieOP
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.

15 Replies

ChausieOP
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
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
ChausieOP
I think I could hardly find a justification for working with these constraints. I will try to delve deeper into these topics even though I have already wasted more time than necessary. Thanks for the support.