I am going through the Next.js official documentation. I am using the App router. On the data fetching patterns page, it's mentioned:
Whenever possible, we recommend fetching data on the server
So, I wrote this simple function:
import 'server-only'
export async function getData() {
const res = await fetch('http://localhost:3333/<endpoint>');
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error('Failed to fetch data')
}
return await res.json();
}
But the api I need to call, require the jwt token in the authorisation header, and I can't access localStorage
on server-side.
So, the next thing I did is, I made my function take the token as an input parameter:
import 'server-only'
export async function getData(token) {
const res = await fetch('http://localhost:3333/<endpoint>', {
headers: {
Authorization: `Bearer ${token}`
}
});
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error('Failed to fetch data')
}
return await res.json();
}
But the problem here is, in order to use this function, I need to import this in my client component, which is an unsupported pattern. (I tried this, and I am getting the relevant error.)
If I need to import this function, I will have to eventually make the data-fetching code run on client environment only, which is against the first recommendation (whenever possible, fetch data on server).
My question here is:
- Is it possible to somehow pass the current request context(including http headers), to the function that needs to run on server, so that I can extract the token out on the server?
- Or, am I just trying to break the pattern here? Is it more like, for protected data, I should not fetch it on server side, but on the client side?
I am considerably new to Next.js or frontend dev in general. I am trying to get around this since yesterday, and am finally looking for help.