Nextjs 12 is released with a new feature called Middlewares. It allows us to run code before a request is completed. We can use this feature for protected routes.
Setting up
You can follow this repo for a simple setup.
Then create a new folder that groups all protected routes and create a _middleware.ts file. For example, I have named the folder user since it's all user personalized routes.
pages
│ _app.tsx
| index.tsx
│ ....
└───user
│ │ _middleware.ts
│ │ dashboard.tsx
│ │ settings.tsx
Add this code:
import jwt from "@tsndr/cloudflare-worker-jwt";
import { NextRequest, NextResponse } from "next/server";
/**
* Verifies the user's JWT token and returns the payload if
* it's valid or a response if it's not.
*/
export async function middleware(request: NextRequest) {
const token = request.cookies["sb:token"]; //'sb:token' is the default cookie name
if (!token || !(await jwt.verify(token, process.env.SUPABASE_JWT_SECRET!))) {
return NextResponse.redirect("/login", 302); // If a user is not authenticated (either no token was send, or the token is invalid) redirect the user to the homepage where they will be presented with a log-in screen
}
return NextResponse.next(); // continue the middleware chain https://nextjs.org/docs/api-reference/next/server#nextresponse
}
This code checks if the cookies set by supabase is valid.
And now dashboard
, settings
pages require authentication now without adding any code in them, or wrapping in HOC. 🎉
Top comments (0)