My site paths are like –
- https://www.example.com/us/en/products
- https://www.example.com/us/es/products
- https://www.example.com/us/en/categories
- https://www.example.com/us/es/categories
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
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
i18n/request.ts:
[code]/[locale]/page.tsx
messages/de.json
messages/en.json
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:
You need to set up your folder structure to handle dynamic routes for country codes and language codes.
Here’s a breakdown:
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
Example with getServerSideProps
If you need to fetch data based on the route parameters, you can use getServerSideProps:
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;
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: