How to protect routes in Next JS

Bawantha Rathnayaka
3 min readJul 3, 2023

some applications allow previewing of some pages based on their authentication state.

In this article, you’re going to learn how to implement protected routes in the Next js application.

In Next.js, you can protect routes by using middleware. Middleware functions are functions that run before the actual route handler and can be used to perform tasks such as authentication, authorization, and validation.

To protect routes using middleware in Next.js, you can follow these steps:

Create a middleware function

First, create a middleware function in the src that will be responsible for checking if the user is authenticated or authorized to access the route.

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {

const isAuthenticated = request.cookies.get('isAuthenticated');
if(!isAuthenticated){
if (request.nextUrl.pathname.startsWith('/project')) {
return NextResponse.rewrite(new URL('/login', request.url));
}

if(request.nextUrl.pathname.startsWith('/favourites')){
return NextResponse.rewrite(new URL('/login', request.url));
}

if(request.nextUrl.pathname.startsWith('/profile')){
return NextResponse.rewrite(new URL('/login', request.url));
}
} else {
if (request.nextUrl.pathname.startsWith('/login')) {
return NextResponse.rewrite(new URL('/', request.url));
}
}
}

The middleware function takes a request parameter of type NextRequest, which represents the incoming HTTP request. It is responsible for checking the authentication status of the user and redirecting them to the appropriate page based on their authentication status.

Inside the function, the code first retrieves the value of the isAuthenticated cookie from the request using request.cookies.get('isAuthenticated'). This value represents the authentication token or flag indicating whether the user is authenticated or not.

If the authToken is falsy (i.e., not present or empty), it means the user is not authenticated. In this case, the code checks the pathname property of the nextUrl property of the request object to determine the current page the user is trying to access.

If the pathname starts with '/project', '/favourites', or '/profile', it means the user is trying to access a protected page. In such cases, the code uses NextResponse.rewrite to redirect the user to the login page by creating a new URL with '/login' appended to the current URL.

On the other hand, if the authToken is truthy (i.e., present and not empty), it means the user is authenticated. In this case, the code checks if the pathname starts with '/login'. If it does, it means the user is already on the login page. In such cases, the code uses NextResponse.rewrite to redirect the user to the home page by creating a new URL with '/' appended to the current URL.

Overall, this middleware function ensures that only authenticated users can access certain protected pages and redirects unauthenticated users to the login page. Similarly, it redirects authenticated users away from the login page to the home page.

Conclusion

If you have a lot of routes in your application that you don’t want to be accessible to users that are not authenticated, all you have to do is repeat the process in these individual routes.

Thank you for reading this article, I hope it has helped you understand how to implement protected routes in Next.js.

--

--

Bawantha Rathnayaka

I write about my experiences as a Software Engineer and the tech I use daily. portfolio - https://bawanthathilan.vercel.app/