Redirects in Composable Setup Part 1
Introduction
If you have attended the recently held Sitecore Symposium 2022, you know very well the direction Sitecore is taking. Composable is the future! Keeping up with this theme, you have started setting up composable solution for your project. Chances are you are using Next.js which is the next big thing in Front-End framework because it provides static site generation and makes the application quick. You now want to implement easy to maintain Redirects using Sitecore CMS in conjunction with Next.JS Storefront application. You want to allow flexibility to add/remove/update redirects to Content Author and still want to update static redirects that get generated at build time on Next.js.
What to do?
The answer is relatively simple.
First, you would setup templates using Sitecore JSS from Next.JS app and create Redirect Items in the CMS. Then you will need to do an API call before the build step is run in order to generate a JSON file that hosts the latest Redirects mappings from CMS.
You read this file from within Next.JS and build. This in turn, will generate static redirects.
How to do it?
Step 1: Templates and Items for CMS
Next.JS requires a specific structure when reading redirects either from the code or a file. You can read more on Next.JS redirects support here. For the sake of simplicity, in this blog we will only cover a simple scenario of redirecting from one path to another.
Keeping in line with the structure, create two template definition items in the Next.Js /sitecore/templates folder.
1. RedirectCode.sitecore.ts
2. Redirect.sitecore.ts
Deploy the newly created templates to the CMS using the command jss deploy app --acceptCertificate {certificateThumbprint} -c -d .
Next, create related items in the CMS using these 2 templates and create a couple redirect settings items.
Don t forget to publish these items and their related templates.
Step 2: Create a PowerShell script to Call the API and Create a RedirectMappings.json file
My solution is hosted on Azure App Service and is deployed to CI/CD pipelines. Hence, I have created a simple PowerShell script that calls the recently created API and puts response data into the RedirectMappings.json file. Some values live in DevOps Library variable for ease of use:
- SITECORE_API_HOST: this is your Sitecore CD server url.
- SITECORE_REDIRECTS_ROOT: this is the ID of your parent Item under which all the Redirect settings item live.
Step 3: Read from the RedirectMappings.json file
Now that everything else is setup, it's time to read the RedirectMappings.json file in Next.JS
Note: Do not forget to import the file like this:
const redirectData = require("./RedirectMappings.json");
That is all for Part 1. We have laid out the groundwork for generating data that will eventually feed into the RedirectMappings.json file.
In Part 2, we will go through the steps of coding and configuring the back-end Sitecore solution to generate the data.
Cheers till then!