How to access the full custom session in a middleware?
Hi! I’m trying to access my full custom session inside a middleware, but it seems like getCookieCache() doesn’t return my custom session data.
Currently, I’m calling betterFetch('/api/auth/get-session') from the middleware as a workaround, but I’m wondering if there’s a better or more efficient way to directly access the complete session (including custom fields) within middleware?
Any tips or best practices would be greatly appreciated. Thanks in advance!
5 Replies
getCookieCache() only checks for a cookie, it does not return session data, beacuse calling for session in middleware is not really optimized because you would query your database in literally every single request. That's why you should do light protection with cookie in middleware, and then eventually protect/get user info in your routes.
I've used getCookieCache() but I can't get the session, whereas with getSessionCookie() everything works perfectly. My problem is that I want to access the full session without using the db.
What's stopping you from using getSessionCookie then? It also only checks for a session cookie in your middleware to avoid making database and api calls
What do you mean by getting the full session?
I want to use session.user.role to redirect the user according to role, but getSessionCookie only retrieves the cookie
That's the point. You shouldn't do that in middleware, get full session in your routes