Published on

How to do Subdomain based Redirection in Next.js

Authors

For taking care of redirection we usually go with path based redirection and use services like Dub.sh

But there are some edge cases in which you might want to do subdomain based redirection. Let's build a simple Next.js app for such cases.

To keep, things simple, we'll be using Vercel's Edge Config to manage our redirection links

Let's get started 🧑‍🔧

Dependency

Create a new Next.js app using the following command and configure it based on your preferences.

npx create-next-app@latest

You can delete the pages/index.js or pages/index.tsx file since we won't need that anyway (And it'll throw an error because of the below wildcard route)

Then install the Vercel Edge config SDK

npm i @vercel/edge-config

And then create and configure your Vercel's Edge Config Store in the env properly

# .env.local
EDGE_CONFIG=https://edge-config.vercel.com/ecfg_...?token=...

In my case, I had this in my store

{
    "redirect_links": {
        "qsite": {
            "paths": {
                "/signup": "https://app.qsite.co",
                "*": "https://qsite.co"
            }
        },
        "an": {
            "paths": {
                "/about": "https://AshikNesin.com/about",
                "*": "https://AshikNesin.com"
            }
        }
    }
}

Creating Helper file: Getting subdomain from URL

We'll also create a helper for @/utils/get-subdomain.js to get the subdomain from the url string

export const getSubdomain = url => {
    let domain = url;
    if (url.includes("://")) {
        domain = url.split('://')[1];
    }
    const subdomain = domain.split('.')[0];
    return subdomain;
};

export default getSubdomain;

Setting up wildcard route

Now create a new file [[...slug]].js in pages directory.

The above file will be used for all the routes. You can think of this as a wildcard route declaration.

import getSubdomain from '@/utils/get-subdomain';
import { get } from '@vercel/edge-config';
export default function WildcardRoute(props) {
    return null;
}

export async function getServerSideProps(context) {
    const host = context.req.headers.host;
    const slug = `/${(context.params.slug || [])
        .filter((item) => item !== "slugs")
        .join("/")}`;

    const subdomain = getSubdomain(host)

    const configStore = await get('redirect_links')

    const redirectRules = configStore[subdomain];

    let redirectUrl = redirectRules?.paths?.[slug];

    if (!redirectUrl && redirectRules?.paths?.['*']) {
        redirectUrl = redirectRules?.paths?.['*']
    }

    return {
        redirect: {
            permanent: false,
            destination: redirectUrl
        },
    };
}

And that's it.

You can now start your local server by running npm run dev

And then try out your redirections. One interesting thing that I've learned recently is that you can use subdomain in localhost

So if your Next.js app runs on http://localhost:3000 and you can append http://example.localhost:3000 and that will be considered as how a real subdomain works.

I've also created a GitHub repo for you to play around.

Happy subdomain-based redirections!