Next13 app-router: How to get request headers on client page comp?
All my pages are client components because I want to use page transitions and need to wrap them in a provider from framer-motion. But I also now need request headers on specific pages. How would you do that? Any ideas?
5 Replies
You could read on the server and then pass it to the client as props
how would you read it on the server?
@Helge Are you using Express for the server? If so, you can use "req.get" to access the request header. Alternatively, you can access header in next.js api route with "req.headers". Next.js also allows you to access incoming request headers inside of your components by using "import { headers } from 'next/headers';"
@hutajoullach thanks for the tip. Importing headers does not work as my page is a client comp and headers from next/headers is required in a server comp
@hutajoullach going the api route might be an option I didn’t try yet
I'm using npm package to access the user's ip address in the req headers in this api route, and then attaching to response. If you can not access certain header objs, you could try to find a module for it.
https://github.com/hutajoullach/nextjs-threejs-pin-dropping-app/blob/main/src/pages/api/ip-data.ts