Refresh Session Cookie for Next.js Server Components with Middleware

Jon Meyers
InstructorJon Meyers
Share this video with your friends

Social Share Links

Send Tweet

Server Components cannot set cookies in the Next.js App Router. In this lesson, we implement middleware to refresh expired Supabase sessions.

Middleware runs immediately before the route is loaded. By using it to refresh our user's session, we ensure it is valid by the time it loads the Server Component and attempts to fetch data from Supabase.

Code Snippets

Refresh expired sessions

supabase.auth.getSession();

Resources

Instructor: There's a small bug with our Auth logic where when the cookie expires and the user refreshes the page, the cookie is removed putting them in a logged out state. This is because back over in our server component, where we're creating a server component client with these cookies from Next.js, we only have read access to these cookies.

When we try to select all of those tweets, Supabase recognizes that that cookie has expired and refreshes it, but since our server component has no way to update that cookie value, it remains that expired token which gets removed from the browser. Now this is only the case for server components, so client components, route handlers, server actions, and middleware can all set a new cookie for a refreshed session, but there's no way to currently do this in server components.

Since we can do this in middleware, we want to create a new file at the rootmost part of our application called middleware.ts. In here we want to export this middleware function which takes a request and creates a response, then passes those along to the createMiddlewareClient function from our Superbase auth helpers package.

Now, since this Superbase client can now modify this request and response, we can call the Superbase.auth.getSession function which will refresh the session if it's expired, and then return this response which will load our server component route, but this cookies function will contain that updated cookie with a fresh session from Superbase.

Now, in our application, when we log in, a cookie is set for our user's session. Once this session has expired, our middleware function will refresh that session in the background. The only time our user should be logged out is when they choose to click the logout button.