Tuesday, May 31, 2022

Different Ways of Handling Redirects in Sitecore Headless JSS NextJS App

 There are several ways to handle custom redirects in NextJS app for Sitecore Headless.


1. Using redirects configurations defined on next.config.js file

We can use NextJS provided redirect functionality for this. We can either define these directly on the next.config.js file's "redirects" section OR can move that to a separate file and include it like below.



NOTE: Needs to include redirects.js file onto next.config.js to get the ...redirectsConfig
const redirectsConfig = require('./src/next-config/redirects');


2. Using Sitecore Redirect Template item

We wanted a way to provide a method to add redirects in case editors wanted to add that url into dynamically generated menus on the site.

So we decided to take the custom Redirect App Route template with RedirectURL field in it.


When this page is requested, we check the RedirectURL field value and do the redirect from getServerSideProps method on [[...path]].tsx page.

This called handling redirects from server side in NextJS app.

Code will look like something below:






3. Using redirects defined in a separate tree section in the Sitecore content tree

This will allow to add multiple redirects without actually having to have a Redirect Sitecore Item defined/created.

This will be same as existing SXA OR Url Rewrite module item structure with separate redirects defined.

But we will use GraphQL to retrieve those data using Sitecore Layout Service and then do the necessary redirects from NextJS server side.

Expect a separate blog post on this in future.


4. Using Vercel app redirects


Vercel also supports defining redirects in Vercel itself.