Skip to main content
Version: next

Create custom redirections

How to create custom redirections in Front-Commerce

Create custom redirections

Front-Commerce is using the Express server to handle requests. This means that you can use any Express middleware to create custom redirections.

info

You can find an example of a custom redirection middleware in the FrontCommerce Remix skeleton.

In this guide, we will create a custom express middleware that will handle redirections.

Create a new file to declare the middleware

Let's start by creating a new file that will store all our middleware logic.

export default function redirections() {
return (req, res, next) => {
const urlRequest = req.url;
if (urlRequest.startsWith("/old-url")) {
const newUrl = urlRequest.replace("/old-url", "/new-url");
res.redirect(newUrl);
} else {
next();
}
};
}

This simple middleware will redirect any request that starts with /old-url to /new-url.

Register the middleware in the server

Now that we have our middleware, we need to register it in the server.

For more information about the startExpressServer function, you can check out the Server API reference.

import { startExpressServer } from "@front-commerce/remix/server/express";
import redirections from "./server/redirections";

startExpressServer([redirections]);

Test the redirection

Now, start the server, go to http://localhost:4000/old-url and you should be redirected to http://localhost:4000/new-url.

This is a simple example, but you can use this approach to create more complex redirections like loading redirections from a file (csv, xml ...).