Protected routes using Next.js Edge Middleware & Supabase

Intro
Next.js now provides middleware functionality, allowing us to execute code before a request is processed — at the edge. We can inspect the request coming from the client, and modify the response. We’ll make use of this to check for a cookie on protected routes, and redirect if the client doesn’t contain the cookie. Handling the redirect at the edge, rather than the client, improves the user experience by preventing protected content from being delivered to the client, which prevents flashes of content, client side redirects, and improves performance.
Step 1: Setting the cookie
I’ll be using Supabase, but the concepts are the same regardless of your auth provider. The first step is to set an auth cookie. Supabase makes this easy by providing a way to listen for auth changes, and a function for setting the cookie. Setting the cookie needs to happen on the server, so we’ll make use of a Next.js api route.
First, add the above code to start listening for auth changes. When the user signs in, or signs out, we will make a request to an endpoint that will add or remove the cookie. We need to send the Supabase Session
, and Event
in the body of our request.
Supabase makes setting the cookie impressively clean. We just give it the req
and res
, and it handles the rest.
Step 2: Checking for the cookie in middleware
The last step is to check for the cookie in our middleware. Next.js makes this very simple, just add a file named middleware.ts
(or .js
), in the same directory that your pages directory exists.
The above code checks if the client is requesting the /dashboard
page, and if it is we check if a cookie named sb-access-token
exists. If it doesn’t we redirect the user to the home page. ezpz.
Conclusion
Supabase and Next.js make protecting routes at the edge effortless. I’m really excited about the current edge-boom that the web is going through. It allows us to create better UX solutions, and is a huge win for performance. If you want to keep up with the latest in webdev make sure to follow me here and on Twitter @Kolbysisk. 🙏