Force fetch cache in dev (middleware)
Answered
Large oak-apple gall posted this in #help-forum
Large oak-apple gallOP
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
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
28 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
@Large oak-apple gall
Large oak-apple gallOP
Ah yes, yet another thing that doesnt work properly because middleware is forced to edge runtime even on classic server 😀
dw, nextjs 15 will be normal
Large oak-apple gallOP
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
Large oak-apple gallOP
So what you suggest in my case is to make fetch request to /api/get-redirects that itself fetches my initial /api/globals/redirects ?
yea..
its weird
ik
go through this part btw
he explains why they did what they did
Large oak-apple gallOP
But then how to use cache in /api/get-redirects? Cache whole route? Cache only fetch request inside route?
cache inside the route
like do the caching you were doing in middleware, in the /get-redirects handler
Answer
Large oak-apple gallOP
It works, thanks