Blogs

Tools

Quick Links

Mridul.tech

How to add Next JS Redirect

Mridul Panda

Mridul Panda

Feb 10, 2023

·

3 Min Read

How to add Next JS Redirect
Next JS Redirect

Redirects are one of the essential features of a web app. With redirects, you can redirect a user to the login page if the user is not logged in. You can add a redirect from the old URL to your new URL. There are so many ways you can use the redirect. In this article, you will learn how to add Next JS Redirect.

There are 3 ways to redirect a user to another page in Next JS. Let’s check them one by one.

Next JS Redirect with next.config.js

In Next JS we have next.config.js where we can add our redirect paths with redirects key. Let’s check one example –

module.exports = {
  async redirects() {
    return [
      {
        source: '/old',
        destination: '/new',
        permanent: true,
      },
    ]
  },
}

The async method redirects anticipate receiving an array of objects with source, destination, and permanent properties

  • source – This is the incoming path pattern
  • destination – This is the path where you want to redirect the source
  • permanent – It accepts two values true or false. if true, the 308 status code will be used, instructing clients and search engines to keep the redirect in their caches indefinitely; if false, the 307 status code, which is transient and not cached, will be used.

Next JS Dynamic Path Redirect

You can add redirects for dynamic URL routes. With this, all the paths in that dynamic route will redirect to new dynamic routes. Example:

{
  source: '/blogs/:slug',
  // Only Matched parameters can be used in the destination
  destination: '/articles/:slug',
  permanent: false
}

Redirect to external URL

The destination key can also be an external URL. But the source can’t be. In this example /links will redirect to https://links.mridul.tech which is an external link.

{
  source: '/links',
  destination: 'https://links.mridul.tech',
  permanent: false
}

Wildcard Path Matching for Redirect

Use * after a parameter to match a wildcard route. After that /blog/:slug will include /blog/a/b/slug. so in our example /blog/a/b/slug will redirect to /article/a/b/slug

{
  source: '/blog/:slug*',
  destination: '/article/:slug*',
  permanent: false
}

Check out More examples on path matching for redirects on Next JS Docs.

Also Read: How to Highlight Code Syntax in Next JS

Next JS Redirect with useRouter Hook

Nextjs includes a built-in hook called useRouter. You can reroute the user using the useRouter hook. The function component contains the useRouter hook code. In the below example, we will redirect the user to /about after clicking on the button on the UI.

import { useRouter } from 'next/router';

const Home = () => {
  let router = useRouter();

  // condition base redirecting
  function redirect() {
    router.push('/about');
  }
  return (
    <div>
      <button onClick={redirect}>Redirect to about</button>
    </div>
  );
};

export default Home;

Also Read: How to Generate ZIP with File Links in Next JS and React JS

Next JS Redirect with Next JS Middleware

With Next JS 12, we have middleware support. Before a request is processed, middleware enables you to run code. Then, depending on the incoming request, you may change the answer by rewriting, redirecting, changing the request or response headers, or directly replying.

Let’s redirect users who are not logged in to the redirect page with Next JS Middleware. The file name will be middleware.js

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

export async function middleware(req) {
  // Token will exist if user logged in
  const token = localStorage;
  const { pathname } = req.nextUrl;

  // Allow the request if the following is true...
  if (pathname.includes('/api/auth') || token) {
    return NextResponse.next();
  }

  // Protected Routes
  if (!token && pathname !== '/login') {
    return NextResponse.redirect('/login');
  }
}

Also Read: How to Add Google Analytics in NextJS

Which is the best way?

  • If you want to redirect users based on login then the middleware method is perfect.
  • But if you want the redirect based on button click then the useRouter method is appropriate.
  • Otherwise, the next.config.js is the best way to handle redirecting in the Next JS. In this way, you can handle dynamic page redirects as well.

You may also like

How to add Google Web Stories in Next JS

How to add Google Web Stories in Next JS

Dec 14, 2023

·

10 Min Read

In the fast-paced digital world, user engagement is key to the success of any website. One effective way to captivate your audience is by incorporating Google Web Stories into your Next JS website. These visually appealing and interactive stories can make your content more engaging and shareable. In this comprehensive guide, we’ll walk you through […]

Read More

How to send Emails in Next JS for Free using Resend

How to send Emails in Next JS for Free using Resend

Nov 10, 2023

·

7 Min Read

Sending emails in web applications is a crucial feature, and in this article, we will explore how to send Emails in Next JS for free using Resend. Next JS is a popular framework for building React applications, and Resend is a handy tool for email integration. By the end of this guide, you’ll have the […]

Read More

How to add Google Login in Next.js with Appwrite

How to add Google Login in Next.js with Appwrite

Nov 01, 2023

·

7 Min Read

Are you looking to enhance user authentication in your Next.js application? Integrating Social Login with Appwrite can be a game-changer. Add Google Login to your Next.js app with Appwrite. This article will guide you through the process, and practical tips to add Google Login in Next.js with Appwrite. GitHub Code: Google Login in Next.js with […]

Read More

JavaScript Project Ideas to Boost Your Portfolio

JavaScript Project Ideas to Boost Your Portfolio

Oct 13, 2023

·

3 Min Read

JavaScript is the backbone of web development, and mastering it is essential for any aspiring developer. While learning the basics is crucial, building real-world projects is the key to solidifying your knowledge. In this comprehensive guide, we’ll present a diverse range of JavaScript project ideas that cater to different skill levels and interests. These projects […]

Read More

How to Generate robots.txt in Next JS?

How to Generate robots.txt in Next JS?

Oct 05, 2023

·

4 Min Read

In the world of web development and search engine optimization (SEO), ensuring that your website is easily accessible and properly indexed by search engines is paramount. One essential tool that aids in this process is the creation of a robots.txt file. In this comprehensive guide, we, the experts, will walk you through the process of […]

Read More

How to Generate Sitemap in Next JS?

How to Generate Sitemap in Next JS?

Sep 28, 2023

·

8 Min Read

In today’s digital landscape, optimizing your website’s SEO is crucial to attracting more organic traffic and ranking higher on search engine result pages (SERPs). One essential aspect of SEO is creating a sitemap, which helps search engines crawl and index your website efficiently. If you’re using Next JS for your website development, this guide will […]

Read More

Do you want more articles on React, Next.js, Tailwind CSS, and JavaScript?

Subscribe to my newsletter to receive articles straight in your inbox.

If you like my work and want to support me, consider buying me a coffee.

Buy Me A Coffee

Contact Me ☎️

Discuss A Project Or Just Want To Say Hi?
My Inbox Is Open For All.

Mail : contact@mridul.tech

Connect with me on Social Media

Contact Art