skip to Main Content

My site paths are like –

or –

https://www.example.com/[countryCode]/[languageCode]/products

Though libraries like – next-intl provides a way to deal with languages only but not if it has some previous country code attached to it.

Let me know any pointer on this.

2

Answers


  1. Finally it works. App Router setup without i18n routing
    https://next-intl-docs.vercel.app/docs/getting-started/app-router/without-i18n-routing

    middleware.ts

    import { NextResponse } from 'next/server';
    import type { NextRequest } from 'next/server';
    
    export function middleware(request: NextRequest) {   
      const requestHeaders = new Headers(request.headers);
      const url = new URL(request.url);
      const locale = url.pathname.split('/').filter(Boolean)[1];
      requestHeaders.set('locale', locale);
    
      const response = NextResponse.next({
        request: {
          headers: requestHeaders,
        },
      });
    
      return response;
    }
    

    i18n/request.ts:

    import { getRequestConfig } from 'next-intl/server';
    import { headers } from 'next/headers';
    
    export default getRequestConfig(async () => {
      // Provide a static locale, fetch a user setting,
      // read from `cookies()`, `headers()`, etc.
    
      const locales = ['en', 'de'];
      const headersList = headers();
      const l = headersList.get('locale') || '';
      
      let locale = 'en';
      if (locales.includes(l)) {
        locale = l;
      }
    
      return {
        locale,
        messages: (await import(`../messages/${locale}.json`)).default,
      };
    });
    

    [code]/[locale]/page.tsx

    import { useTranslations } from 'next-intl';
    
    export default function HomePage() {
      const t = useTranslations('HomePage');
    
      return <h1>{t('title')}</h1>;
    }
    

    messages/de.json

    {
      "HomePage": {
        "title": "Hallo Welt!"
      }
    }
    

    messages/en.json

    {
      "HomePage": {
        "title": "Hello world!"
      }
    }
    
    Login or Signup to reply.
  2. To create custom routes in Next.js that support countries and languages, such as the examples you provided, you can leverage Next.js’s dynamic routing capabilities. Here’s how you can set it up:

    1. Setup Dynamic Routes

    You need to set up your folder structure to handle dynamic routes for country codes and language codes.

    pages/
    [countryCode]/
     [languageCode]/
      products.tsx
      categories.tsx
    

    Here’s a breakdown:

    • [countryCode] and [languageCode] are dynamic route segments that will match any value.
    • products.tsx and categories.tsx are the pages for your routes.
    1. Access Route Parameters

    In your page components (e.g., products.tsx), you can use Next.js’s useRouter hook or getServerSideProps / getStaticProps to access the dynamic route parameters.

    Example with useRouter

    // pages/[countryCode]/[languageCode]/products.tsx
    import { useRouter } from 'next/router';
    const Products = () => {
    const router = useRouter();
      const { countryCode, languageCode } = router.query;
    
      return (
        <div>
          <h1>Products</h1>
          <p>Country: {countryCode}</p>
          <p>Language: {languageCode}</p>
        </div>
      );
    };
    
    export default Products;
    

    Example with getServerSideProps
    If you need to fetch data based on the route parameters, you can use getServerSideProps:

    // pages/[countryCode]/[languageCode]/products.tsx
    import { GetServerSideProps } from 'next';
    
    interface Props {
      countryCode: string;
      languageCode: string;
    }
    
    const Products = ({ countryCode, languageCode }: Props) => {
      return (
        <div>
          <h1>Products</h1>
          <p>Country: {countryCode}</p>
          <p>Language: {languageCode}</p>
        </div>
      );
    };
    
    export const getServerSideProps: GetServerSideProps = async (context) => {
      const { countryCode, languageCode } = context.params as { countryCode: string; languageCode: string };
    
      // Fetch data based on the countryCode and languageCode
    
      return {
        props: {
          countryCode,
          languageCode,
        },
      };
    };
    
    export default Products;
    
    1. Handling Links
      When creating links to these pages, you should construct the URLs using the dynamic segments:

      import Link from ‘next/link’;

      const Navigation = () => {
      return (

      US – English Products

      US – Spanish Products

      US – English Categories

      US – Spanish Categories

      );
      };

      export default Navigation;

    2. Optional: Locale and Country Detection
      If you need to detect and redirect based on the user’s location or preferred language, you can use server-side logic in getServerSideProps or a middleware approach.

    For server-side redirection based on locale or country:

    // pages/[countryCode]/[languageCode]/index.tsx
    import { GetServerSideProps } from 'next';
    
    const Home = ({ countryCode, languageCode }: { countryCode: string; languageCode: string }) => {
      return (
        <div>
          <h1>Welcome</h1>
          <p>Country: {countryCode}</p>
          <p>Language: {languageCode}</p>
        </div>
      );
    };
    
    export const getServerSideProps: GetServerSideProps = async (context) => {
      const { countryCode, languageCode } = context.params as { countryCode: string; languageCode: string };
    
      // Example logic to redirect if needed
      if (!['us', 'uk'].includes(countryCode)) {
        return {
          redirect: {
            destination: '/us/en',
            permanent: false,
          },
        };
      }
    
      return {
        props: {
          countryCode,
          languageCode,
        },
      };
    };
    
    export default Home;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search