Blog>
Snippets

Localization with Dynamic Routes

Create an example on how to handle localization and internationalized routing in Next.js 14 with dynamic routes.
import { useRouter } from 'next/router';

// This is a page component with dynamic routing enabled for localization
export default function LocalizedPage() {
  const router = useRouter();
  const { locale, query: { slug } } = router;

  // Render your content based on the locale and dynamic slug
  return (
    <div>
      <h1>{`The current locale is: ${locale}`}</h1>
      <p>{`The dynamic part of the URL (slug) is: ${slug}`}</p>
    </div>
  );
}
This snippet creates a localized page component using Next.js dynamic routing. It imports useRouter from Next.js, extracts the locale and slug from the router, and renders content accordingly.
import { locales, defaultLocale } from './config' // Presume config file exists with all locales and a default

function getPathForLocale(path, locale) {
  if (locale === defaultLocale) return path;
  return `/${locale}${path}`;
}

export default function redirectToLocalizedPath(req, res) {
  const detectedLocale = req.acceptsLanguages(locales) || defaultLocale;
  const localizedPath = getPathForLocale(req.url, detectedLocale);
  res.redirect(302, localizedPath);
}
This code defines a helper function to prepend the locale to a given path if it's not the default. Then, a function for redirecting to a localized path based on the detected locale from the request is provided.
// Assume you have a file or API that returns localized content based on locale
import getContentForLocale from './content-api'

export async function getServerSideProps({ params, locale }) {
  // Fetch localized content for the current locale and slug
  const content = await getContentForLocale(locale, params.slug);

  // Pass the localized content to the page component via props
  return { props: { content } };
}
This snippet shows how to retrieve localized content server-side in Next.js using 'getServerSideProps'. It fetches the content based on the current locale and dynamic slug, which are part of the context parameter.