Contentful logo

Contentful Community

Search in all locales

Hello,
I have urls on my app that look like this https://myapp.com/<locale>/<entry_slug>
To build a page, I use contentful API to search for an entry with slug=<entry_slug>

I’d like to enable localization for the slug field so an entry could look like:

{slug:{ en: 'mySlug-en', fr: 'mySlug-fr' }

Now let’s say the user is on page:
https://myapp.com/en/mySlug-en

My issue is that if the user changes the locale to let’s say french, then the language switch will navigate to:
https://myapp.com/fr/mySlug-en

But mySlug-en won’t match any entry for locale fr.

If contentful API could search for slug=mySlug-en in any locale then I could get my content and redirect the user to https://myapp.com/fr/mySlug-fr

If you data is stored as you describe:

{slug:{ en: 'mySlug-en', fr: 'mySlug-fr' }

then you can search Contentful for the slug field using the match operator like so:

https://cdn.contentful.com/spaces/<space_id>/entries?
   content_type=<ct_id>&
   fields.slug[match]=mySlug&
   locale=<locale_code>&
   access_token=<access_token>

And you can search in either fr locale or the en locale and get back the entry.

One question: when the user switches from en to fr, couldn’t you make the application change the search string from mySlug-en to mySlug-fr programmatically prior to searching Contentful?

Hope this helps!

But fields.slug[match]=mySlug will search for slugs that contain ‘mySlug’, right? What I’d need is an exact match in any language.

when the user switches from en to fr , couldn’t you make the application change the search string from mySlug-en to mySlug-fr programmatically prior to searching Contentful?

How would I get the english slug for my content? Only Contentful has this information. Maybe my first message was not clear. I’d like to have translated urls. So basically I’d have urls like:
English URL: https://myapp.com/en/hello
French URL: https://myapp.com/fr/bonjour
Both pointing to the same Contentful entry. When the user directly enter our site with one of those urls, this is ok. But if a user gets to https://myapp.com/en/hello and wants to switch language to “fr”, I see 2 solutions:

  1. Fetch fr slug for the entry so the link to fr page is correct. This solution is a bit more complicated to implement for us because our language switch is generic. It just changes the language in the current URL.
  2. Keep the language switch generic and just change the url to https://myapp.com/fr/hello then fetch content from Contentful looking for slug hello in any language. From Contentful response see that fr slug is “bonjour” and redirect the user to https://myapp.com/fr/bonjour

Would solution 2 make sense to you? Maybe I just missed something?