Next.jsWeb DevelopmentSoftware EngineeringDeveloper Tooling

Protecting Routes in Next.js 13

With the evolution of the App Router in Next.js, the framework has become even more robust, offering developers enhanced control over…

Table of Contents (9)

With the App Router, Next.js gives developers more control over routing and a more efficient way to protect routes. This guide covers protecting routes with the App Router (Next 13.4), including Middleware, exportMode, unstable_cache and more. It's intended for senior developers with a good understanding of Next.js and React.

Complete examples can be found in the associated Gist: https://gist.github.com/zachshallbetter.

The App Router

Next.js is a popular framework for building React applications that support server-side rendering, static site generation, and incremental static regeneration. One of its features is the App component, which lets you customize the rendering of your pages and share state across them.

The App Router lets developers handle routing more centrally. It provides a single place (the app directory) to define routes and their corresponding components, which makes routes easier to manage and allows for advanced routing features like transitions, nesting, and route protection.

Changes in configuration

Replacing output with exportMode

The output option in next.config.js is deprecated and replaced by exportMode. Usage:

module.exports = {
  exportMode: 'your-value',
};

Replacing generateStaticParams with getStaticPaths

The generateStaticParams function is no longer required and replaced by getStaticPaths. Usage:

export async function getStaticPaths() {
  // Your logic here
}

Replacing fetch with unstable_cache

The fetch function is no longer automatically memoized and replaced by unstable_cache. Usage:

import { unstable_cache } from 'next/fetch';

export async function getServerSideProps() {
  const data = await unstable_cache('your-api-url');
  return { props: { data } };
}

Replacing revalidateTag with revalidate

The revalidateTag function is no longer available and has been replaced by revalidate. Usage:

export async function getStaticProps() {
  // Your logic here
  return {
    revalidate: 10, // Time in seconds
  };
}

Protecting pages, components and APIs with Middleware

The Route Handlers feature is no longer supported and replaced by Middleware. Here's how to use Middleware to protect pages, components, and APIs:

import { NextResponse } from 'next/server';

export function authMiddleware(req) {
  // Add your own logic here to check if the user is authenticated
  const userIsAuthenticated = checkUserAuthentication();

  if (!userIsAuthenticated) {
    return NextResponse.redirect('/login');
  }

  return NextResponse.next();
}

This defines an authMiddleware function that checks if the user is authenticated and redirects them to the login page if not. We import it into our pages and API routes and apply it using authMiddleware(req).

Using the App component to protect routes in Next.js 13.4

The App component is a special component that Next.js uses to initialize pages. It receives props such as Component, pageProps, router, and err, and it can return any React element. The Component prop is the active page component, and the pageProps prop is the props that are passed to it. The router prop is an instance of the Next.js router, which exposes methods and properties such as push, replace, pathname, query, and asPath. The err prop is an optional error object that is only defined when an error occurs during rendering.

With the App component you can wrap your pages with a common layout or a provider component, for example to add a header and a footer to all your pages, or to provide a global context or a theme to your application. To use it, create a file called _app.js (or _app.tsx if you are using TypeScript) in the pages directory and export a default function or class component.

To protect routes that require authentication or authorization, we can use the App component to check the user’s status and redirect them to a login page or an error page if they are not authorized to access the current page. This takes two hooks: useRouter and useEffect. The useRouter hook returns the router object that we can use to access the current route information and perform navigation. The useEffect hook lets us run a side effect after the component renders.

The basic idea is to use useEffect to check the user's status and compare it with the required status for the current route. If they don't match, we can use router.replace to redirect the user to another page. We can also use router.events.on('routeChangeStart', callback) to listen for route changes and perform the same check before rendering the new page. Here is an example of this logic in the App component:

import { useRouter } from 'next/router';
import { useEffect } from 'react';

function MyApp({ Component, pageProps }) {
  const router = useRouter();

  useEffect(() => {
    const handleRouteChange = (url) => {
      // Add your own logic here to check if the user is authenticated
      const userIsAuthenticated = checkUserAuthentication();

      if (!userIsAuthenticated && url === '/protected-page') {
        router.replace('/login');
      }
    };

    router.events.on('routeChangeStart', handleRouteChange);

    return () => {
      router.events.off('routeChangeStart', handleRouteChange);
    };
  }, []);

  return <Component {...pageProps} />;
}

export default MyApp;

This is a simple way to protect routes with the App component. You may need to customize it, for example to store and retrieve the user’s token differently, to determine the required status for each route another way, or to handle edge cases and errors.

The full code:

import { useRouter } from 'next/router'
import { useEffect } from 'react'

function getUserStatus(token) {
  if (token === 'admin') {
    return 'admin'
  } else if (token === 'user') {
    return 'user'
  } else {
    return 'guest'
  }
}

function getRequiredStatus(pathname) {
  if (pathname === '/admin') {
    return 'admin'
  } else if (pathname === '/profile') {
    return 'user'
  } else {
    return 'guest'
  }
}

export default function App({ Component, pageProps }) {
  const router = useRouter()

  function checkAuth() {
    const token = localStorage.getItem('token')
    const userStatus = getUserStatus(token)
    const requiredStatus = getRequiredStatus(router.pathname)

    if (userStatus !== requiredStatus) {
      if (userStatus === 'guest') {
        router.replace('/login')
      } else {
        router.replace('/error')
      }
    }
  }

  useEffect(() => {
    checkAuth()
  }, [])

  useEffect(() => {
    const handleRouteChange = () => {
      checkAuth()
    }

    router.events.on('routeChangeStart', handleRouteChange)

    return () => {
      router.events.off('routeChangeStart', handleRouteChange)
    }
  }, [])

  return <Component {...pageProps} />
}

Using Middleware.js to protect routes in Next.js 13.4

Another way to protect routes is to use middleware.js, which lets you run code before rendering a page on both the server and the client. You can use it to perform authentication, authorization, redirection, caching, or any other logic needed before rendering a page.

To use middleware.js, create a file called _middleware.js (or _middleware.ts if you are using TypeScript) in the pages directory and export a default function that receives a NextRequest object and returns a NextResponse object or nothing.

To protect routes with middleware.js, we can use the same logic as in the App component. We check the user’s status and compare it with the required status for the current route. If they don’t match, we use NextResponse.redirect to redirect the user to another page.

Example code for middleware.js:

import { NextRequest, NextResponse } from 'next/server'

function getUserStatus(token) {
  if (token === 'admin') {
    return 'admin'
  } else if (token === 'user') {
    return 'user'
  } else {
    return 'guest'
  }
}

function getRequiredStatus(pathname) {
  if (pathname === '/admin') {
    return 'admin'
  } else if (pathname === '/profile') {
    return 'user'
  } else {
    return 'guest'
  }
}

export default function middleware(req) {
  const token = req.cookies.token
  const userStatus = getUserStatus(token)
  const requiredStatus = getRequiredStatus(req.nextUrl.pathname)

  if (userStatus !== requiredStatus) {
    if (userStatus === 'guest') {
      return NextResponse.redirect('/login')
    } else {
      return NextResponse.redirect('/error')
    }
  }
}

This approach has advantages over using the App component, such as being faster, more flexible, and more secure. It also has limitations: it can't access React components or hooks, and it can't run on older browsers that don’t support ES modules. The official documentation covers middleware.js and its features and caveats in more detail.