How to quickly redirect to another page URL in Next.js

Last updated on September 17, 2023
How to quickly redirect to another page URL in Next.js

To easily redirect to another page URL in Next.js:

  • Static redirect: use the redirects key in next.config.js.
  • In App Router server component: use redirect() from the next/navigation.
  • In pages Router: use useRouter() from next/navigation.
  • In middleware: use NextResponse.redirect() from next/server.
Redirecting to another page or URL in Next.js.
Redirecting to another page URL in Next.js.

To easily redirect to another page URL in Next.js, use the redirects key in your next.config.js file:

// ...
const nextConfig = {
  // ...
  async redirects() {
    return [
      {
        source: '/blog',
        destination: '/',
        permanent: true,
      },
    ];
  },
};

module.exports = nextConfig;

redirects is an async function that returns an array with items that have source, destination, and permanent properties:

  • source: A pattern matching the path of the incoming request.
  • destination: The path you want to redirect to.
  • permanent: If true, Next sets a 308 status code in the redirection response, which tells clients like search engines to cache the redirect from that point onwards. If false, Next will set a 307 status code (temporary redirect) instead, making sure that redirect doesn't get cached.

Note: While 301 and 302 are the popular status codes for permanent and temporary redirects, Next.js uses 307 and 308 because many browsers changed the request method to GET for the destination URL, regardless of the method the client set in the original request to the source. So if POST v1/posts returned a 302 with v2/posts, the next request to v2/posts may end up GET v2/posts instead of POST v2/posts. But with 307 and 308, the browsers are guaranteed to preserve the request method.

Redirect statically with path parameter to page URL

You can use a path parameter like :path to match any path in the source URL and pass it on to the destination URL.

Here, /news/:slug/ will match /news/codingbeauty and redirect to /blog/codingbeauty.

// ...
const nextConfig = {
  // ...
  async redirects() {
    return [
      {
        source: '/news/:slug',
        destination: '/blog/:slug',
        permanent: true,
      },
    ];
  },
};

module.exports = nextConfig;

It doesn't work for nested paths though.

Redirect statically with wildcard path to page URL

To match nested routes, query parameters, and anything else in the source path, use the * character after the path parameter.

// ...
const nextConfig = {
  // ...
  async redirects() {
    return [
      {
        source: '/articles/:slug*',
        destination: '/blog/:slug*',
        permanent: true,
      },
    ];
  },
};

module.exports = nextConfig;

Redirect to another page URL dynamically in Next.js App Router server component

To redirect to another page URL dynamically in a Next.js 13 server component, use the redirect() function from the next/navigation module:

import React from 'react';
import { Metadata } from 'next';
import { redirect } from 'next/navigation';

export const metadata: Metadata = {
  title: 'Next.js - Coding Beauty',
  description: 'Tutorials by Coding Beauty',
};

export default function Page() {
  if (process.env.NEXT_PUBLIC_HOME) redirect('/home');

  return <main>Welcome to Coding Beauty.</main>;
}

The redirect() function redirects the browser to another URL; /home in this case.

Here this happens conditionally, but if the redirect is guaranteed to happen, it will surely prevent any JSX in the page from rendering, and editors like VS Code are smart enough to detect this:

Visual Studio Code can detect when the JSX in a page is unreachable due to a redirect.

Redirect to another page URL dynamically in App Router client component

To redirect to another page URL dynamically in a Next.js client component in the Next.js 13 app directory, use the push() method of the object returned by the useRouter hook from the next/navigation module:

Here we're redirecting from from the /blog path to an external URL:

'use client';

import React, { useEffect } from 'react';
import { useRouter } from 'next/navigation';

export default function Page() {
  const router = useRouter();

  useEffect(() => {
    router.push('https://wp.codingbeautydev.com');
  }, []);

  return <main>Welcome to Coding Beauty.</main>;
}

The useRouter hook returns a Router object that we use to programmatically change the route, resulting in a client-side redirect.

Redirect to another page URL dynamically in Pages Router component

It's like in the App router, but useRouter comes from next/router instead of next/navigation.

To redirect to another page URL dynamically in a Next.js client component in the Pages router, use the push() method of the object returned by the useRouter hook from the next/router module.

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

export default function Home() {
  const router = useRouter();

  useEffect(() => {
    router.push('/fantastic-url');
  }, []);

  return (
    <>
      <Head>
        <title>Amazing URL | Coding Beauty</title>
        <meta name="description" content="Generated by create next app" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.png" />
      </Head>
      <main>
        <p>Coding Beauty</p>
        <h2>Amazing URL</h2>
      </main>
    </>
  );
}

The useRouter hook returns a Router object that we use to programmatically change the route to perform a redirect on the client side.

Next.js >= 12: Redirect to another page URL in middleware

To redirect to another page URL using middleware in Next.js 12.1 and above, use the NextResponse.redirect method from the next/server module in a middleware.ts file.

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

export function middleware(request: NextRequest) {
  const url = request.nextUrl.clone();
  if (url.pathname === '/old-blog') {
    url.pathname = '/new-blog';
    return NextResponse.redirect(url);
  }
}

Here we use request.nextUrl to get the current URL in the Next.js middleware.

You'll place middleware.ts file in the same level as your pages directory - which could be the root directory, or src, if enabled.

middleware.ts is at the same level as the pages directory.
middleware.ts is at the same level as the pages directory.

The reason why this only works in Next.js 12.1 above is because starting from Next.js 12.1, relative URLs are not allowed in redirects with NextResponse.redirect() or NextResponse.rewrite().

Next.js 12: Redirect to another page URL in middleware

To redirect to another page URL dynamically using middleware in Next.js 12, use the NextResponse.redirect() method from the next/server module in a _middleware.js file inside the pages folder or a subfolder where you want the middleware to work:

import { NextResponse, NextRequest } from 'next/server';
export async function middleware(request, event) {
  const { pathname } = request.nextUrl;
  if (pathname == '/') {
    return NextResponse.redirect('/hello-nextjs');
  }
  return NextResponse.next();
}

Key takeaways

  • In Next.js, there are several ways to quickly redirect to another page URL.
  • For static redirects, you can use the redirects key in the next.config.js file. It allows you to define source and destination paths with options for temporary or permanent redirects.
  • Path parameters (e.g., /blog/:slug) and wildcard paths (e.g., /blog/:slug*) can be used to match and redirect nested routes or query parameters.
  • In a Next.js App Router server component, you can use the redirect() function from the next/navigation module to dynamically redirect to another URL.
  • In the Next.js client component, you can use the push() method from the useRouter hook in the next/navigation (Next.js 13) or next/router (Next.js 12 and below) module to programmatically change the route and perform a client-side redirect.
  • For middleware in Next.js 12.1 and above, you can use the NextResponse.redirect() method from the next/server module in a middleware.ts file.
  • In Next.js 12 middleware, you can use the NextResponse.redirect() method in a _middleware.js file inside the pages folder or a subfolder.
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also