next.js: Caching data doesn't work in middleware

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: linux
      Arch: x64
      Version: #22 SMP Tue Jan 10 18:39:00 UTC 2023
    Binaries:
      Node: 16.17.0
      npm: 8.15.0
      Yarn: 1.22.19
      pnpm: 7.1.0
    Relevant packages:
      next: 13.3.1-canary.3
      eslint-config-next: N/A
      react: 18.2.0
      react-dom: 18.2.0

Which area(s) of Next.js are affected? (leave empty if unsure)

No response

Link to the code that reproduces this issue

https://codesandbox.io/p/sandbox/wandering-worker-7g6q59

To Reproduce

  1. open codesandbox example
  2. open console
  3. see such log image

Describe the Bug

React cache() doesn’t work in middleware.

Expected Behavior

In middleware should be used cached data for same request.

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 38
  • Comments: 26 (6 by maintainers)

Most upvoted comments

Hey, I created an issue and discussion on this a while ago.

I inspected Next.js code and it seems that caching is just not available inside Edge Function.

I understand the reason, but eventually it will force people out of Vercel’s infrastructure.

Please upvote the discussion and let’s make Middleware on Edge Function optional.

Found another workaround for this (Next 14.2.5), make a route in the api folder and use it to proxy the request. For example, to cache a request to https://www.example.com/api/users, do:


/api/mwcache/users/route.js (example path, named it like this out of convenience)

import { NextResponse } from "next/server";

export async function GET(request) {
  const fetchResp = await fetch(
    "https://www.example.com/api/users",
    { next: { revalidate: 3600 } }  // Or any other cache rule you want
  )
  // Minimal example but you can forward also headers and response status and other things as you need them
  return NextResponse.json(await fetchResp.json());
}

middleware.js

export default async function middleware(request) {
  const cachedResp = await fetch(`${process.env.HOST}/api/mwcache/users`);  // Set HOST in .env
  const cachedData = await cachedResp.json();
  // Do things with you cached data...
}

{HOST}/api/mwcache/users is not cached and will get called every time but https://www.example.com/api/users will be cached as per the rules you set.

To add to this, if you wrap your fetch requests in React’s cache - like

import { cache } from 'react'

export const getUser = cache(async (): Promise<User | null> => {
  const res = await fetch(`${API_ENDPOINT}/user/?`, {
    headers: {
      Cookie: `cookieId=${cookies().get('cookieId')?.value}`,
    },
  });
  if (!res.ok) {
    return null;
  }
  const data = await res.json();

  return data
});

And then try to use this function in your middleware, it doesn’t work, and you get a TypeError: (0 , react__WEBPACK_IMPORTED_MODULE_1__.cache) is not a function error…

We’re not able to use a fetch without a cache (as we depend on cookies), so need to use React cache for memoization, but this doesn’t work with middleware at all.

Would really be good to look into this, currently we’re going to have to duplicate all of our functions so that there’s a version of them without the wrapping cache (for use exclusively in the middleware.ts)

Plus, because middleware hits for multiple things on each route - the same request to the API could be fired around 3/4 times per page load (since there’s no memoization!)

Found another workaround for this (Next 14.2.5), make a route in the api folder and use it to proxy the request. For example, to cache a request to https://www.example.com/api/users, do:

/api/mwcache/users/route.js (example path, named it like this out of convenience)

import { NextResponse } from "next/server";

export async function GET(request) {
  const fetchResp = await fetch(
    "https://www.example.com/api/users",
    { next: { revalidate: 3600 } }  // Or any other cache rule you want
  )
  // Minimal example but you can forward also headers and response status and other things as you need them
  return NextResponse.json(await fetchResp.json());
}

middleware.js

export default async function middleware(request) {
  const cachedResp = await fetch(`${process.env.HOST}/api/mwcache/users`);  // Set HOST in .env
  const cachedData = await cachedResp.json();
  // Do things with you cached data...
}

{HOST}/api/mwcache/users is not cached and will get called every time but https://www.example.com/api/users will be cached as per the rules you set.

This is the best workaround I have found so far. You set up cached API route and fetch the absolute path from your middleware.

Seems like a pretty big issue since the middleware is used a lot by us for checking for legacy links which aren’t going to change, so we really need to cache the db responses.

On 14.1.0

Just to add my voice to others, I too was surprised by this, along with the fact that middleware can’t be opted out of the edge runtime which therefore blocks the direct calling of databases in many cases.

I suspect this “edge only” implementation is going to be why this can’t be implemented. It follows that if these are serverless functions they can’t have any form of persistent state.

I read elsewhere that this is a deliberate design decision to prevent people overloading middleware, but for the cynical among us it looks more like an attempt to force people onto vercel. After all, if deploying to a normal nodejs environment is fully supported (as per the docs) there is really no need to force this limitation.

Please, at least let us opt out of edge middleware so we can use caching and direct DB access.

Any news on this? Cache does not work in standalone mode too. Lack of cache and “different fetch behaviour” comes as a surprise.

…although re-reading this issue I’m not sure it describes my issue. The title seems like it’s about caching data (ie. fetch cache) but the actual description is “React cache() doesn’t work in middleware” which is not the same as caching responses in fetch.

Is this issue about the fact that fetch requests are not cached in the middleware?

Is there an ongoing issue or timeline for this? I want to use my middleware to cache redirects from my CMS, which is not possible at the moment, I can’t use unstable_cache inside my src/middleware.ts. Any workarounds?

Exactly my use case (Payload CMS). We need CMS managed redirects that also forward search params. When doing this on RSC level, we lose SSG since search params is considered a dynamic API.

So I was looking into fetching the redirects from middleware and it looks like caching is not even supported in middleware, only through a cached route handler (really not the same). That will be an additional round trip Edge <-> Serverless Function, which really bugs me.

Looks like they want to push Edge Config hard

Here my workarround using header instead of calling proxy api if your data is light

export default async function middleware(request) {
const response = NextResponse.next()

  try {
    const fetchResp = await fetch(
      "https://www.example.com/...",
    )
    const data = await fetchResp.json()
  
    if (data) {
      response.headers.set('dataKey', JSON.stringify(data))
    }

    return response
  } catch (error) {
    ...
  }
}

You can retrieve these data in server or client componant

Found a workaround, make your data fetching server actions, cache those and call the functions in your middleware

What I’m doing now, is my middleware uses fetch() to call an api route, that api route uses a cached fetch to my CMS.

@merfire Its actually quite simple. Middleware is in this kinda weird state atm where it forces you to be on an edge runtime which does not have any caching. The main reason being they dont want you to do any sort of operations which needs any sort of node functions or any thing needing caching to be done in the middleware and instead take it to a page level. But it seems as they realized this is a bad idea and are working on bringing back edge runtime.

That feature is essential for me