Install using bunx shadcn@latest add @remix-utils/middleware-session.
The session middleware let's you save a session object in the Router context so you can access it in any loader and ensure you're always working with the same Session instance.
By default the middleware will automaticaly commit the session at the end of the request, but you can customize this behavior by passing a second argument to the createSessionMiddleware function.
let [sessionMiddleware, getSession] = createSessionMiddleware(sessionStorage, shouldCommit);
The shouldCommit function will be called at the end of the request with the previous session data and the session data before the request, if it returns true the session will be committed, if it returns false the session will be discarded.
If you want to commit the session only if the session data changed you can use a library like dequal to compare the session data.
import { dequal } from"dequal";
let [sessionMiddleware, getSession] = createSessionMiddleware( sessionStorage, (previous, next) => !dequal(previous, next), // Only commit if session changed );
Or you can use a custom function to compare the session data, maybe only if some specific fields changed.
Install using
bunx shadcn@latest add @remix-utils/middleware-session.The session middleware let's you save a session object in the Router context so you can access it in any loader and ensure you're always working with the same Session instance.
To use it, you need to create a session storage object and pass it to the middleware.
Then you can use the
sessionMiddlewarein yourapp/root.tsxfunction.And you can use the
getSessionfunction in your loaders to get the session object.By default the middleware will automaticaly commit the session at the end of the request, but you can customize this behavior by passing a second argument to the
createSessionMiddlewarefunction.The
shouldCommitfunction will be called at the end of the request with the previous session data and the session data before the request, if it returnstruethe session will be committed, if it returnsfalsethe session will be discarded.If you want to commit the session only if the session data changed you can use a library like
dequalto compare the session data.Or you can use a custom function to compare the session data, maybe only if some specific fields changed.
Author
Sergio XalambrÃ