APIcrud

Tutorials, source codes and solutions on React, Next.js, Vercel, AWS and more

Want to take your web development skills to the next level and build a SaaS app? Follow me to build fast and learn how to balance between technical debt, delivery speed to launch quickly and validate early. Let's network and learn together!

Brought to you by AdrianteoycLinkedin

Become A Redirect Master In Nextjs

Good day, here are 3 ways you can redirect web pages to another internal or external web page using Nextjs.

  1. Client-side redirect
    Useful for quick single web page redirect. This is a quick workaround to solve problems of the page before your boss or customer notice the problem on the page.

  2. Redirect in Server Components, Route Handlers, and Server Actions
    The redirect function allows you to redirect the user to another URL and can be used in Server Components, Route Handlers, and Server Actions.

  3. Nextjs next.config.js redirect
    You can create redirect in the next.config.js file. Use this if you are migrating websites and need to redirect many web pages

Let me share the soucre codes below.

  1. Client-side redirects

The useRouter hook allows you to programmatically change routes inside Client Components.

"use client";
import { useRouter } from "next/navigation";
import { useEffect } from "react";

export default function page() {
  const router = useRouter();
  useEffect(() => {
    router.push("/redirected-page");
  });

  return <div>Can still be seen for a few seconds</div>;
}

Overall, this component immediately redirects the user to "/redirected-page" when it is rendered, but there might be a short delay before the redirect happens. So user will still see the page for a few seconds. This is just a temporay redirect to use in case of emergency 🚑.

  1. Next.js 14 introduces the redirect() and permanentRedirect() function which can be use in Server Components, Route Handlers, and Server Actions
redirect(path, type);
//and
permanentRedirect(path, type);

Both function accepts two arguments:

  • path: The URL to redirect to. Can be a internal URL or external URL
  • type: 'replace' will replace the page in history, 'push' (default) will add the redirect URL to the browser history

The redirect function return a 307 (Temporary) HTTP redirect when you use it.

The permanentRedirect will serve a 308 (Permanent) HTTP redirect response. So if user clicks on it via Google search, Google will understand(soon) that this page is permantently redirected and will use your new URL in future search results.

import { redirect } from "next/navigation";
export default function page() {
  redirect("/redirected-page");
  return <div>Will not show up</div>;
}
  1. Nextjs next.config.js file redirect
    If you have a lot of web pages to redirect, wildcards to redirect or need to redirect to another domain, this is the best solution to create it inside the next.config.js file.
// next.config.js file
/** @type {import('next').NextConfig} */
const nextConfig = {
  async redirects() {
    return [
      {
        // source is the incoming request path pattern.
        source: "/huat",
        // destination is the path you want to route to.
        destination: "/redirected-page",
        // permanent true or false - if true will use the 308 status code which instructs clients/search engines to cache the redirect forever, if false will use the 307 status code which is temporary and is not cached.
        permanent: true,
      },
      {
        source: "/huatnow",
        destination: "https://www.apicrud.com",
        permanent: true,
      },
      //redirect wildcards - For example, redirect /old-blog/blog-one to /blog/blog-one
      {
        source: "/old-blog/:path*",
        destination: "/blog/:path*",
        permanent: false,
      },
    ];
  },
};

export default nextConfig;

When it comes to choosing which redirect method to use in Next.js, it largely depends on your specific needs. Hope my source code above helps you to become a redirect master in Next.js