Get Browser Locale

A helpful utility function to get browser locale.

get-locale.ts

ts
1export function getBrowserLocale(): string {
2  if (typeof window === "undefined") {
3    return "en-US";
4  }
5
6  const nav = window.navigator;
7  let locale: string = "en-US";
8
9  if (nav.languages?.length) {
10    // Chrome, Firefox
11    locale = nav.languages[0];
12  } else if (nav.language) {
13    // IE, Safari
14    locale = nav.language;
15  }
16
17  return locale;
18}

Usage

One good use case is displaying number in locale format.

tsx
1<span>
2  {Intl.NumberFormat(getBrowserLocale(), {
3    notation: "compact",
4    maximumFractionDigits: 1,
5  })
6  .format(100000)
7  .toString()}
8</span>

This displays 100k for locale en-US and 1L for locale en-IN


Loved this post?

Comments

Interested in
working
with me?

Let's Connect

Stay in touch 👇

© 2021 - 2026 itsrakesh. v2.