Next.js Discord

Discord Forum

Workaround on caching a request with Headers

Unanswered
Indian mackerel posted this in #help-forum
Open in Discord
Avatar
Indian mackerelOP
i have a fetch request that i need to protect, i am currently using Authorization header to do that but like this i cannot cache the request, how do i work around this? is there a way to "force-cache" a request even if it uses headers? if not possible why this limitation?

basically i need to have a route in my express backend accessible only by the nextjs server, i also want to be able to cache the request

The reason i need to cache the request:
I need this request to display information in my page, this information doesnt need to change frequently, so i need to kinda SSG-like render the page (i cannot use SSG because my navbar has information based on getServerSession which is a server function) and i dont want to use useSession neither to keep as much as i can server-side

11 Replies

Avatar
European sprat
if it's a fetch and is using a static authorization header, why can't you cache it?
Avatar
Indian mackerelOP
i try but it doesnt get cached
this is the code
export async function getGroups() {
    const groupsData = await (
        await fetch(process.env.NEXT_PUBLIC_SERVER_URL + "/groups", {
            method: "GET",
            headers: {
                Authorization: process.env.SUPERSECRET,
            },
            cache: "force-cache",
            next: {
                tags: ["groups"],
            },
        })
    ).json();

    return groupsData;
}
Avatar
Indian mackerelOP
.
Avatar
European sprat
it doesn't cache in production?
show the full code for where that fetch function is used
Avatar
Indian mackerelOP
this is my file structure
/[type]
  page.js
  /[group]
    /[post]
      page.js

inside /[type]/page.js and /[type]/[group]/[post]/page.js

...
export default async function Page({ params: { type } }) {
    const groupsData = await getGroups();
...
Avatar
European sprat
and it doesn't cache in production builds?
Avatar
Indian mackerelOP
no it doesnt
and i call it for each post so if i have 350 posts i'll have 350 exactly equal requesta
Avatar
Indian mackerelOP
still have found no fix