Server-Side Redirecting in Next.js

Server-Side Redirecting in Next.js

Enhancing User Experience and Security with Server-side Redirection in Next.js

Table of contents

No heading

No headings in the article.

Next.js is a powerful framework for building React-based applications.
One of its awesome features is server-side rendering SSR.

This allows for faster initial load times, better SEO, and a more seamless user experience. An aspect of SSR is redirecting the user object based on certain conditions, such as whether they are logged in.
In this blog post, we will go over how to use the getServerSideProps function in Next.js to perform server-side redirecting.

First, let's take a look at the code snippet provided:

//login.tsx
import { GetServerSidePropsContext } from "next"
import auth from "utils/auth.util"

export const getServerSideProps = async ({ req}: GetServerSidePropsContext) => {
      const { token, userId } = await auth(req)

       if (token && userId) return { redirect: { destination: "/", permanent: false, }, }

       return { props: {} }
}

export default function Login() {
     return ...
}
//utils/auth.util.ts
import { getLoginSession } from "lib/auth.lib";
import { IncomingMessage } from "http";

export default async function auth(req: IncomingMessage) {
  const session = await getLoginSession(req);
  const token = session?.token as string;
  const userId = session?.["https://hasura.io/jwt/claims"]?.[
    "x-hasura-user-id"
  ] as string; // Uses Hasura 

  return { token, userId };
}

In this example, we use the getServerSideProps function to check whether the user is authenticated by calling an auth function and passing in the req object. This function returns an object with token and userId properties. If the token and userId are truthy, It means the user is authenticated, and we return an object with a redirect property. This property is an object that contains a destination property and a permanent property. The destination property is a string representing the URL to redirect the user, and the permanent property is a boolean that determines whether the redirect is permanent.

If the user is not authenticated, the function returns an object with only a props property, which is set to an empty object. This tells Next.js that there is no redirect to be performed, and the page should be rendered.

On the home route where the user is not authenticated, we can also redirect the user to the login page as follows:

//index.tsx
import { GetServerSidePropsContext } from "next"
import auth from "utils/auth.util"

export const getServerSideProps = async ({ req}: GetServerSidePropsContext) => {
      const { token, userId } = await auth(req)

       if (!token && !userId) return { redirect: { destination: "/login", permanent: false, }, }

       return { props: {} }
}

export default function Home() {
     return ...
}

It's worth noting that the getServerSideProps the function is only run on the server, meaning the redirect will happen before the page is rendered on the client. This can enhance the user experience and security of your application.

In summary, using the getServerSideProps function in Next.js allows you to perform server-side redirects based on user authentication or any other logic you need before the page is rendered. This can enhance the user experience and security of your application.