Conditional redirection in Next.js with Examples

In this comprehensive tutorial, we’ll explore how to implement Conditional Redirection in Next.js using both server-side and client-side approaches. Next.js offers developers various ways to handle redirection within applications effectively. Leveraging conditional redirection facilitates a personalized user experience by directing visitors to pages based on specific criteria.

Conditional redirection in Next.js

Table of Contents

 

Basic Redirect Function

Let’s start with a basic redirect function. This function detects whether a user is authenticated and redirects them accordingly.

function redirectTo(destination, { res, statusCode = 301 } = {}) {
  if (res) {
    res.writeHead(statusCode, { Location: destination });
    res.end();
  } else {
    if (window.location.pathname !== destination) {
      window.location.replace(destination);
    }
  }
}

You can invoke this function depending on the authentication state like so:

const userIsAuthenticated = false; // Replace with actual authentication check
const destination = "/login"; // Replace with your target path

if (!userIsAuthenticated) {
  redirectTo(destination);
}

Conditional Redirection Example

Now let’s delve into a practical example where user roles dictate the redirection process. Assume you have an application with multiple roles – admin and member.

function redirectToRoleBasedPage(userRole) {
  switch (userRole) {
    case "admin":
      redirectTo("/admin/dashboard");
      break;
    case "member":
      redirectTo("/member/dashboard");
      break;
    default:
      redirectTo("/login");
  }
}

Output:


Redirecting to appropriate dashboard or login page based on user role...

Server-side Redirection

Server-side redirection is useful, especially for handling initial rendering and SEO purposes. Here’s how to implement it within getServerSideProps in Next.js to verify a user’s role before rendering a page:

export async function getServerSideProps(context) {
  const { req, res } = context;
  const userRole = "admin"; // Replace with actual role check logic
  
  if (userRole !== "admin") {
    redirectTo("/unauthorized", { res, statusCode: 302 });
    return { props: {} };
  }

  // Rest of your server-side logic...
}

Output:


Server-side redirection to /unauthorized if the user is not an admin.

Client-side Redirection

Client-side redirection can be handled through the useEffect hook in functional components. This approach is suitable for actions that occur after component mounting.

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

const useClientSideRedirect = (user) => {
  const router = useRouter();

  useEffect(() => {
    if (!user.isAuthenticated) {
      router.push('/login');
    }
  }, [user, router]);
};

Output:


Client-side redirection to /login if the user is not authenticated upon component mounting.

Summary

Conditional redirection is a powerful tool in Next.js that enables developers to control user flow within an application. Whether you opt for server-side redirection with getServerSideProps or client-side with hooks, both methods ensure a seamless and dynamic user experience when used appropriately. Remember to use these redirection techniques to enhance user engagement and maintain secure access to various parts of your application.

References

This tutorial aimed to provide an understanding of Conditional Redirection in Next.js. Following these guidelines and examples should enable you to implement redirection that responds dynamically to user interactions and states. Keep in mind that user experience and application security should always be at the forefront when designing these redirection strategies.