Handling URL Redirections in Next.js 14: Using `next.config.js` and `getServerSideProps` Methods

57 views

"In Next.js 14, you can handle URL redirections by leveraging the next.config.js file for server-side redirection or by using the getServerSideProps in your page components. Below are the methods you can use:

Using next.config.js for Redirections

In Next.js 14, you can define redirects in the next.config.js file. This is a straightforward way to handle redirections at the server level.

  1. Add Redirects in next.config.js:
// next.config.js

module.exports = {
  async redirects() {
    return [
      {
        source: '/post/:postId', // URL pattern with postId
        destination: '/post/fetch-slug-here', // Target URL pattern - you will need to map it dynamically
        permanent: true,
      },
    ];
  },
};

Note: The above example shows the basic structure for adding redirects. You need to implement the logic to dynamically map postId to slug.

Using getServerSideProps for Redirection

For more dynamic needs, where you need to fetch the slug based on postId from a database or some other data source, you can use getServerSideProps.

  1. Create a Dynamic Route and Handle Redirection in the Page Component:
// pages/post/[postId].js

import { useRouter } from 'next/router';

// Implement your logic to fetch slug based on postId
async function getSlugFromPostId(postId) {
  // Replace with your actual data-fetching logic, e.g., from a database
  const slugMap = {
    1: 'example-post-1',
    2: 'example-post-2',
    3: 'example-post-3',
  };
  return slugMap[postId] || null;
}

// This function will run on the server side
export async function getServerSideProps(context) {
  const { postId } = context.params;

  // Fetch the slug based on postId
  const slug = await getSlugFromPostId(postId);

  if (!slug) {
    return {
      notFound: true,
    };
  }

  return {
    redirect: {
      destination: `/post/${slug}`,
      permanent: true,
    },
  };
}

// This empty component is only here for Next.js to load the server-side function
export default function RedirectPost() {
  return null;
}

Explanation:

  1. Dynamic Route:

    • Create a file named pages/post/[postId].js which matches URLs like /post/123.
  2. Fetching the Slug:

    • Implement a function getSlugFromPostId to map postId to slug. This function can query a database or use any logic necessary to return the appropriate slug.
  3. Server-side Redirection:

    • In getServerSideProps, retrieve the postId from the URL parameters.
    • Use getSlugFromPostId to fetch the slug.
    • If the slug does not exist for the given postId, return notFound: true to display a 404 page.
    • If the slug is found, return a redirect object with the destination set to the new URL containing the slug.
  4. Empty Component:

    • Export a default empty component, as its rendering logic is managed by the getServerSideProps function.

Conclusion:

Using these methods, you can redirect URLs with postId to URLs with slug dynamically in a Next.js 14 application. For static redirects or simple cases, use the next.config.js method. For dynamic requirements, use getServerSideProps in your page components."