</>StackKit
</>StackKit

Developer tutorials & guides

Next.js middleware: authentication and redirects

A comprehensive guide to Next.js middleware: authentication and redirects.

S

StackKit Team

3 min read649 words
#next.js#tutorial#guide#nextjs#middleware#auth#security
{
  "title": "Next.js Middleware: Authentication and Redirects",
  "description": "Learn how to use Next.js middleware for authentication and redirects. This tutorial covers setup, API routes, and examples.",
  "content": "
# Next.js Middleware: Authentication and Redirects
=====================================================

Next.js middleware is a powerful feature that allows you to run code before a request is processed. This can be useful for authentication, redirects, and more. In this tutorial, we'll explore how to use Next.js middleware for authentication and redirects.

## What is Next.js Middleware?
---------------------------

Next.js middleware is a feature introduced in Next.js 12. It allows you to run code before a request is processed, giving you the ability to modify the request, redirect the user, or even return a response.

### Enabling Middleware

To use middleware in your Next.js project, you need to create a file in the `middleware` directory. For example, you can create a file called `auth.js` in the `middleware` directory.

## Authentication Middleware
-------------------------

Let's create an example of authentication middleware. We'll use this middleware to check if a user is authenticated before allowing them to access a page.

```javascript
// middleware/auth.js
import { NextResponse } from 'next/server';

export async function middleware(request) {
  const token = request.cookies.get('token');

  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  return NextResponse.next();
}

In this example, we're checking if a token exists in the cookies. If it doesn't, we redirect the user to the login page. If it does, we allow the request to proceed.

Applying Middleware to Pages

To apply this middleware to a page, you can add the following code to the page file:

// pages/dashboard.js
import { useMiddleware } from 'next/hooks';
import { authMiddleware } from '../middleware/auth';

export default function Dashboard() {
  // Page content
}

export const getServerSideProps = useMiddleware(authMiddleware);

However, this approach requires you to add the middleware to every page that needs authentication. A better approach is to use the middleware directory to apply the middleware to all pages.

You can create a file called [...nextauth].js in the middleware directory:

// middleware/[...nextauth].js
import { authMiddleware } from './auth';

export { authMiddleware };

This will apply the authentication middleware to all pages.

Redirect Middleware


Let's create an example of redirect middleware. We'll use this middleware to redirect users from an old URL to a new URL.

// middleware/redirects.js
import { NextResponse } from 'next/server';

export async function middleware(request) {
  const url = request.url;

  if (url.startsWith('/old-url')) {
    return NextResponse.redirect(new URL('/new-url', request.url), 301);
  }

  return NextResponse.next();
}

In this example, we're checking if the URL starts with /old-url. If it does, we redirect the user to /new-url with a 301 status code.

Applying Redirect Middleware to Pages

To apply this middleware to a page, you can add the following code to the page file:

// pages/_middleware.js
import { redirectsMiddleware } from '../middleware/redirects';

export { redirectsMiddleware };

However, this approach requires you to add the middleware to every page that needs redirects. A better approach is to use the middleware directory to apply the middleware to all pages.

You can create a file called [...nextredirects].js in the middleware directory:

// middleware/[...nextredirects].js
import { redirectsMiddleware } from './redirects';

export { redirectsMiddleware };

This will apply the redirect middleware to all pages.

Conclusion


In this tutorial, we've explored how to use Next.js middleware for authentication and redirects. We've created examples of authentication middleware and redirect middleware, and shown how to apply them to pages.

Middleware is a powerful feature in Next.js that can help you simplify your code and improve performance. By using middleware, you can keep your pages focused on rendering content, while handling authentication and redirects in a separate layer.

We hope this tutorial has helped you understand how to use Next.js middleware for authentication and redirects. If you have any questions or need further assistance, please don't hesitate to ask. " } ```

Tagged

#next.js#tutorial#guide#nextjs#middleware#auth#security
S

Written by

StackKit Team

StackKit Team is a software engineer and technical writer covering developer tools, programming languages, and modern web development.