What does this article teach? #
This article is showing you how I managed to translate dynamic pages' urls, in other words slugs. Usually we use same slug for each translation of a dynamically created content. In this post I'm going to show you how you can connect different slugs for each locale, how to query them and how to solve it by creat a dynamic language switcher component in Next.js 13 App Router.
How to Query For Different Slugs #
Localization using Sanity.io is pretty simple. However, you may need to utilize some plugins if you want to scale your app. I have applied document-internationalization strategy to my blog posts using this plugin
Everthing is cool so far. The problem occurs when user switches the language in a blog page. The biggest problem for me was how to redirect the user to the other translated version of the document. Keep in mind our slug is our main parameter for data fetching in the /[lng]/blogs/[slug]
page. Suppose the url is /en/how-to-solve-language-switch-in-localized-sanity-documents
so when a user switches the language it'll become /tr/how-to-solve-language-switch-in-localized-sanity-documents
. However, there is no document with the slug parameter how-to-solve-language-switch-in-localized-sanity-documents
for the tr language in your query. At first I tried to solve this by being careful to use the same slug for all languages of a document in Sanity, but then I wanted to adapt the slugs according to the languages for a better SEO experience.
Reconsidering App Router Layout #
The problem here is we need different slugs for each locale for better SEO compatibility. However, in this case I have a different problem. In my project set up there I had a layout.ts
which is in my (pages) folder and wraps all the pages including [slug].ts
. The header which wraps language switcher component is rendered in this layout. So one language switcher for all pages seemed to be a good idea at the beginning.
This switcher doesn't seem to be dynamic for my [slug].ts
page so I decided to reconsider my page foldering.
This is the new folder structure I have planned.
Refactoring Old Language Switcher #
And I now moved layout with static language switcher options away from my [slug].ts
page. All I need to do was to adjust my getPageData
function which was initially used to fetch blog post and pass it as a prop and add other translated documents slugs as headerLinks
.
And pass these headerLinks
as dynamicLinks
prop to the LanguageSelector.ts
component.
And voila !