Next.js Discord

Discord Forum

Force fetch cache in dev (middleware)

Answered
Sphecid wasp posted this in #help-forum
Open in Discord
Sphecid waspOP
I want to use fetch request in middleware. I expect it to be cached, so every request will just read value from cache instead of making new request after first time.

However in dev mode cache is not applied, so every page load makes very much lot of requests for every url on page, which takes forever to finish.
Is it possible to force cache in dev mode in this specific function?

Tried to also use unstable_cache, but it errors in middleware

// middleware.ts
import type { NextRequest } from 'next/server'

export default async function middleware(request: NextRequest) {
    const res = await fetch('http://localhost:3000/api/globals/redirects', {
        next: {
            revalidate: 86400,
            tags: ['redirects'],
        },
    })
    const redirects = await res.json()

    const path = request.nextUrl.pathname

    // (if path in redirects) ...
}
Answered by Arinji
like do the caching you were doing in middleware, in the /get-redirects handler
View full answer

33 Replies

stuff in middleware itself cant be cached
what you can do
is make an api route
do your request in there and cache it in the api route
and so the middleware will make uncached requests to the handler which makes cached requests to the external thing
go through this btw
@Sphecid wasp
Sphecid waspOP
Ah yes, yet another thing that doesnt work properly because middleware is forced to edge runtime even on classic server 😀
Sphecid waspOP
But I am on latest canary though
my bad its still in dev ig
the reason they did this is cause they dont eant you making your middleware slow asf with external requests
hence why the very limiting edge runtime
but they realized there can be cases where you neeed nodejs as a runtime
so its being worked on
Sphecid waspOP
So what you suggest in my case is to make fetch request to /api/get-redirects that itself fetches my initial /api/globals/redirects ?
its weird
ik
go through this part btw
he explains why they did what they did
Sphecid waspOP
But then how to use cache in /api/get-redirects? Cache whole route? Cache only fetch request inside route?
like do the caching you were doing in middleware, in the /get-redirects handler
Answer
Sphecid waspOP
It works, thanks
@Sphecid wasp I'm very stuck on this, would you mind sharing some code on how you solved it? I've created an api/route.ts but my cache is skipping.
@Miguel <@220641138267258892> I'm very stuck on this, would you mind sharing some code on how you solved it? I've created an api/route.ts but my cache is skipping.
Sphecid waspOP
I did it like this
I don’t have my laptop here I will check tonight, thank you! So you invalidate the cache as well? When an update in the cms happens?
Sphecid waspOP
Yes, I send webhook to revalidate tag
Great! I got it working now. Thanks