Next js Redirects – Client, Server Side and External Redirection Methods!

We will walk through a detailed guide on variour type of Redirection methods in Next js with various methods. In Next js, we can handle the redirects both on the Client-side as well as on the Server-side. In addition to this external redirects to open the link out of the application in a new tab…

By.

min read

We will walk through a detailed guide on variour type of Redirection methods in Next js with various methods. In Next js, we can handle the redirects both on the Client-side as well as on the Server-side. In addition to this external redirects to open the link out of the application in a new tab is also a popular redirection requirement.

Redirection helps to navigate users from one page to another which can be a static page or a dynamic one. Sometimes we may need to navigate a user to some external source link.

 

Variour Type of Redirections in Next.js

Let’s have a quick look at the ways how redirection works in Next js applications:

– Client-Side Redirects

Client-side redirection is initiated at the browser side using Javascript. This type of redirection is suitable for use cases where page transition occurs after the initial HTML is loaded. They are useful for creating smooth user interactions without full server response. These redirections are achieved by using the next/link or the useRouter hook.

– Server-Side Redirects

Server-side redirection is performed on the server before the HTML page is represented to the client. These type of redirects are ideal and require authentication, dynamic routing, or SEO-related redirects. It occurs on the server before the page is rendered. It can be implemented using res.redirect() in getServerSideProps which we will discuss in the example below.

– External Redirects

External redirection navigated users to external websites or resources. These redirects may serve various purposes like linking to an affiliate site, providing links to documents etc.

 

When to Use Client-Side vs Server-Side Redirects

Client-side redirects are best for internal app navigations where we don’t need to verify anything on the server before redirecting.

Server-side redirects are preferred when:

  • Redirecting from legacy URLs
  • Authentication checks are needed before redirecting
  • Redirecting based on certain status codes
  • SEO requirements – 301, 302 status codes

 

Client-Side Redirect Methods in Next.js

Following are client-side redirection methods with examples:

1. Using next/link

The next/link component provides a href prop which can be used for redirects:

import Link from 'next/link';

export default function Home() {
  return (
    <Link href="/about">
      <a>About Page</a> 
    </Link>
  )
}

 

2. Using next/router

This is the simplest way to redirect in Next.js is by using the redirect function from the next/router module:

import { useRouter } from 'next/router';

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

  const redirect = () => {
    router.push('/about');
  }

  return (
    <button onClick={redirect}>Redirect</button>
  )
}

 

3. Using useEffect

In cases where you want to trigger a client-side redirect after a certain event or user action, the useEffect hook comes in handy:

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

const ProductPage = () => {
  const router = useRouter();

  useEffect(() => {
    if (/* some condition */) {
      router.push('/new-product-page');
    }
  }, []);

  return <p>Product details...</p>;
};

export default ProductPage;

 

4. Using the Redirect Component

The Redirect component from next/link can be used to redirect as shown below:

import { Redirect } from 'next/link';

export default function Home() {
  return <Redirect href="/about" />
}

 

Server-Side Redirect Methods in Next.js

Let’s have a look on the server-side redirection method with the example below:

1. Using getServerSideProps

The getServerSideProps function is used for server-side redirection. We can use this method to conditionally redirect a user before rendering the page. It redirects users by returning a redirect object as shown below:

export async function getServerSideProps(context) {
  if (/* some condition */) {
    return {
      redirect: {
        destination: '/new-page',
        permanent: false,
      },
    };
  }

  return {
    props: {}, // Will be passed to the page component as props
  };
}

const DynamicPage = () => {
  return <p>Dynamic content...</p>;
};

export default DynamicPage;

We can see in the above example if the condition is met only then the user is redirected to the /new-page route. The permanent property decides whether the redirection is permanent (301) or temporary (302).

 

Benefits of getServerSideProps for Redirection

Following are some important benefits of using getServerSideProps for redirection in the Nextjs app:

Fine-Tuned Control: We can handle redirection based on dynamic conditions based on user data.

SEO Integrity: The redirection flow is decided on the server-side so it helps to maintain SEO integrity and prevents potential SEO pitfalls.

Authentication Flow: Server-side redirection plays a crucial role in authentication to ensure a secure and smooth authentication flow.

 

Methods for Implementing External Redirects

Now, we will look into methods of redirection to external resources from next js application with examples:

 

1. Using the window.location Object

The easiest method to redirect users to external sites is by using the window.location object:

const redirectToExternalSite = () => {
  window.location.href = 'https://www.external-site.com';
};

const MyComponent = () => {
  return (
    <button onClick={redirectToExternalSite}>
      Go to External Site
    </button>
  );
};

 

2. Using next/link Component

It is designed primarily for internal linking, but the next/link component can also be used to create links to external sites:

import Link from 'next/link';

const ExternalLink = () => {
  return (
    <Link href="https://www.external-site.com" passHref>
      <a target="_blank" rel="noopener noreferrer">
        Visit External Site
      </a>
    </Link>
  );
};

 

3. Using next/router Module

The next/router module can be used to initiate a client-side redirect to an external URL as shown below:

import { useRouter } from 'next/router';

const redirectToExternal = () => {
  const router = useRouter();
  router.push('https://www.external-site.com');
};

const ExternalRedirect = () => {
  return (
    <button onClick={redirectToExternal}>
      Redirect to External Site
    </button>
  );
};

 

Passing Query Parameters on Redirect

We have discussed how to redirect for various use cases, let’s have a look how to pass query params with the query object:

router.push({
  pathname: '/about',
  query: { name: 'John' }
})

The name query param will now be available on the /about page.

 

HTTP Status Codes on Redirect

By default, redirects are 302 temporary but you can customize the status code:

// 301 permanent redirect
redirect: {
  destination: '/about',
  permanent: true,
}

// 308 permanent redirect
redirect: {
  destination: '/about',
  statusCode: 308,
}

 

Conclusion

With this, we have come to the end of the tutorial where we discussed various ways to implement redirection in the Next js application with the help of examples. We discussed the various use cases for the implementation a correct redirection method out of the Client-side server Side or External with multiple methods.

Client Side redirections help to redirect internally between various pages whereas the Server side redirection helps to decide on conditional redirection and handle various use cases like user authentication.

Leave a Reply

Your email address will not be published. Required fields are marked *