How to get URL value in a NextJS 14 server component

clock icon

asked 2 months ago

message

1 Answers

eye

10 Views

I need to get a value from the URL to fetch data using Nextjs 14 server components.

For example

  • example.com/es/ (production)
  • localhost:3000?locale=es (local development)

I want to get the locale from each of these urls to query data from a headless CMS.

My original idea was to create a custom provider which got the locale from the url, save it to state to be accessed at a component level. I realised whilst having the data in state ready to use, I can't access it in a server component! I don't want to use a client component here to fetch data.

I've tried wrapping the server component in a client component to pass locale as a prop, but that didn't work due to using /app folder.

I've also tried setting a cookie and headers using middleware. This approach kind of worked, but was very temperamental.

What would be the best way to achieve this?

1 Answers

in a Next.js server component, you can get route parameters from params.

Example:

This is the route:

/app/[locale]/page.tsx

url would be

http://localhost:3000/es

Page example:

interface Params {
  locale: string
}

async function MyPage({ params }: { params: Params }) {
  const { locale } = params
  console.log(locale)

  return (
<h1>My page</h1>
  )
}
 

Top Questions