I am currently working on a next.js app and so far so good, all has been going on fine but my client wants a feature that's quite difficult for me to implement.
SO the site is at mysite.com and routes like mysite.com/cars, mysite.com/vehicles, etc
Now my client wants to a dynamic subpath based on the visitor's country e.g. mysite.com/us/cars or mysite.com/uk/cars or mysite.com/ng/cars
I have tried the new i18n feature in next.js 10 but seems like that only works based on user's locale (language).
Is there a way I can programmatically do this or I should leave it to DevOps to deploy to subfolders?
You can accomplish this with dynamic routing.
https://nextjs.org/docs/routing/dynamic-routes
What you'd need to do is to adjust to have a [locale]
folder in your directory structure, so your pages become:
pages/[locale]/cars
or pages/[locale]/vehicles
.
You can then access the active locale with
const router = useRouter();
const locale = router.query.locale;
to determine how to retrieve the content. In the event that you need to statically generate said locales, you can do that as well by placing a
getStaticPaths
function in your pages
https://nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation
Now then, if you're going to ask how to dynamically route based on their current country i.e. redirect once they land on the top level pages, well that is a whole different game.