Skip to main content

Localization detection

In this guide you'll learn how use headers, cookies or URL search parameters for approximating a user's location.

Caution

While it's possible to detect an approximation of the user's locale by reading the header, cookies or URL search params. Shopify only recommends this to improve the experience of the user. Learn more about using header, cookies and URL search params in the overview.

A good example of detecting localization is to show a banner to asking the user if they want to switch country.

A bad example of localization detection is when the user gets automatically redirected.

Other drawbacks of this approach are that page caching ignores locale cookies, headers and URL search params. SEO bots tend to origin from the US, don't have cookies and will not change their accept-language headers.



Anchor to Step 1: Create a utility function that reads the requestStep 1: Create a utility function that reads the request

Create a utility function that reads the request.

Tip

You can use the /app/lib/utils.ts file in the Hydrogen demo store as a point of reference.

The following is an example of extracting the accept-language header from the user request:

/app/libs/utils

/app/lib/utils.js
export function getApproximateLocaleFromRequest(request: Request): Locale {
const url = new URL(request.url);

// Get the accept-language header
const acceptLang = request.headers.get('accept-language');

// Do something with accept language.
// For example:
if(acceptLang.includes('en-US')) {
return {
language: 'EN',
country: 'US',
};
}

// Use the default locale
return {
language: 'EN',
country: 'CA',
};
}

You can use this utility function to trigger analytics or for reading this approximate locale.


Was this page helpful?