DEV Community

mhcrocky for sedecx

Posted on

2 1

Next.js 12 Authentication Middleware with Supabase

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

This code checks if the cookies set by supabase is valid.
And now dashboard, settingspages require authentication now without adding any code in them, or wrapping in HOC. 🎉

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay