I need to get a value from the URL to fetch data using Nextjs 14 server components.
For example
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?
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>
)
}