If you want to access the locale information in your Next.js application, there are a few different approaches you can take depending on whether you're working on the client side or server side.
When working with React components on the client side, you can utilize the useRouter()
hook provided by Next.js to easily retrieve the locale information, including the defaultLocale.
const { defaultLocale, locale, locales } = useRouter()
console.log(defaultLocale)
For server-side rendering using methods like getStaticProps
, getStaticPaths
, and getServerSideProps
, the context object passed to these functions contains the necessary locale information.
export async function getStaticProps({ defaultLocale, locale, locales }) {
console.log(defaultLocale)
// ...
}
Additionally, when using getInitialProps
, you can access the router object from the context to fetch the locale data.
Page.getInitialProps = async ({ router }) => {
const { defaultLocale, locale, locales } = router
console.log(defaultLocale)
// ...
}