user25770779
user25770779

Reputation: 33

How to enable auto redirect when I want to use only domain based routing?

I want to create a nextjs i18 app with subdomain based locale, like-

example.com //It is default locale, on default locale I want to use en fr.example.com de.example.com

I don't want to use prefix like- fr.example.com/fr de.example.com/de

That's why disable the locale prefix. Following is my code-

i18n.ts-

import { notFound } from "next/navigation";
import { getRequestConfig } from "next-intl/server";

const locales = ["en", "fr", "de"];

export default getRequestConfig(async ({ locale }) => {
    if (!locales.includes(locale as any)) notFound();
    return {
        messages: (await import(`../translate/${locale}.json`)).default
    };
});

middleware.ts-

import createMiddleware from "next-intl/middleware";

export default createMiddleware({
    locales: ["en", "fr", "de"],
    defaultLocale: "en",
    localePrefix: "never",
    domains: [
        {
            domain: "dev.localhost:3000",
            locales: ["en"],
            defaultLocale: "en"
        },
        {
            domain: "fr.dev.localhost:3000",
            locales: ["fr"],
            defaultLocale: "fr"
        },
        {
            domain: "de.dev.localhost:3000",
            locales: ["de"],
            defaultLocale: "de"
        }
    ]
});

export const config = {
    matcher: ['/((?!api|_next|.*\\..*).*)']
};

So, here you can see that, I use this localePrefix: "never",. Now it is not auto redirecting.

What I want? I want to auto redirect to subdomain based routing without adding locale prefix. Suppose, detection locale is fr, but I am going to root domain example.com, it automatically should redirect to fr.example.com.

Again suppose, detection locale is en, but I am trying to go fr.example.com it should redirect to example.com, as here I want to use root domain for en locale.

Same as, if I previously switch locale to fr, next-intl is saving this onto cookie, then I try to go example.com, it should redirect to fr.example.com.

Could anyone please help me, I need to understand the whole things. Please say or give minimal example, how can I do that?

Could anyone please help me, I need to understand the whole things. Please say or give minimal example, how can I do that?

Upvotes: 0

Views: 77

Answers (0)

Related Questions