#Localization with App Router
1 messages · Page 1 of 1 (latest)
To achieve localized slugs with Next.js, you can follow these steps:
- Configure your
next.config.jsfile with the locales and defaultLocale:
// next.config.js
module.exports = {
i18n: {
locales: ['en', 'sv'],
defaultLocale: 'en',
},
}
-
Create separate pages for each language and their respective slugs. For example, for the About page, create two files:
pages/en/about.jsandpages/sv/om-oss.js. Similarly, for the Blog page, create two files:pages/en/blog/[slug].jsandpages/sv/blogg/[slug].js. -
In your dynamic route files (e.g.,
pages/en/blog/[slug].jsandpages/sv/blogg/[slug].js), use theuseRouterhook from 'next/router' to access theslugparameter:
// pages/en/blog/[slug].js and pages/sv/blogg/[slug].js
import { useRouter } from 'next/router'
export default function Post() {
const router = useRouter()
const { slug } = router.query
return <h1>Post Slug: {slug}</h1>
}
- For generating static paths with localized slugs, you can use
getStaticPathsin your dynamic route files:
// pages/en/blog/[slug].js and pages/sv/blogg/[slug].js
export const getStaticPaths = ({ locales }) => {
return {
paths: [
{ params: { slug: 'post-1' }, locale: 'en' },
{ params: { slug: 'post-1' }, locale: 'sv' },
],
fallback: true,
}
}
This setup will allow you to have localized slugs for your About and Blog pages in both English and Swedish.
Sources:
- Internationalized Routing (https://nextjs.org/docs/advanced-features/i18n-routing)
- Dynamic Routes (https://nextjs.org/docs/routing/dynamic-routes)