Protected Routes in NextJs 12

Ahmer Patel
2 min readMar 31, 2022

Protected routes allow us to ensure only logged in users can access certain parts of our site which are authenticated. In this post we will create a production level authenticated routes in NextJs by using middlewares.

NextJs being a javascript framework is a absolutely beast when compared to other frameworks. NextJs supports Rust compiler as of October 2021 which makes it 5x faster.

We are going to use the concept of middleware. Middleware is not a new concept , frameworks like express.js use middleware to intercept an http request and process it in someway before it goes to your actual route handler.

Let’s get started

  1. In your project create a file names “_middleware” in the pages directory
Global scoped middleware

2. Inside _middleware.ts you can export a function called “middleware” , this function will access you to the incoming request and allow you to modify it and will run before nextjs renders any page in the pages directory. If want it to run on only specific pages for example you have a page called “dashboard” in the pages directory , you should create file called _middleware inside that specific folder.

Page scoped

This will run before the dashboard page renders.

3. Now inside the _middleware.ts we want to verify if the user is logged in, if the user is logged in we will let the dashboard page renders as usual but if the user authentication failes we will redirect the user back to login page.

import {NextFetchEvent , NextRequest , NextResponse } from ‘next/server’;

export function middleware(req,event) {

const token = req.headers[‘Authorization’]; // can get the token from localstorage or cookies too

const isLoggedIn = validate(token) // an api to backend ,this will return true or false based on auth token.

if(isLoggedIn) {

return new Response(“Access granted”);

}else {

return event.responseWith(NextResponse.redirect(“/login”)); // redirect

}}

Happy coding :)

--

--