Shiva
Shiva

Reputation: 582

How to avoid caching for specific Nextjs API route?

I have nextjs api route /api/auth/signout, it basically just clears the specific cookie and send JSON back.

The problem is, when I deploy project in Vercel, this particular API working first time properly (cookie cleared and giving 200 response) but later it's not working (cookie not cleared and giving 304 response).

I want to know, is there any way to avoid cache only for this route?

What's the best possible way to fix this problem?

Upvotes: 7

Views: 20170

Answers (4)

Erich García
Erich García

Reputation: 1884

Had a very similar problem with a corn API route and fixed it with

export const revalidate = 0;

in the route.js file

Upvotes: 11

j pizzle
j pizzle

Reputation: 41

This is more of an answer to your use-case rather than the title of the question:

I think you should view the signout http endpoint as one that has a side-effect i.e. the destruction of a user session (even though nothing may be happening server-side). For http endpoints that have side-effects, it’s recommended to call them with the appropriate http method that implies that a side-effect will occur e.g. DELETE would be good in this case. By way of the http spec, responses to http DELETE requests shouldn’t be cached.

Upvotes: 1

Shiva
Shiva

Reputation: 582

Added this config on next.config.js

async headers() {
    return [
      {
        source: '/api/<route-name>',
        headers: [
          {
            key: 'Cache-Control',
            value: 'no-store, max-age=0',
          },
        ],
      },
    ];
  },

Upvotes: 4

Christian Hagelid
Christian Hagelid

Reputation: 8355

You can configure Cache-Control header per API endpoint

https://nextjs.org/docs/api-reference/next.config.js/headers#cache-control

In your case, something like this might do the trick:

res.setHeader('Cache-Control', 'no-store')

Upvotes: 3

Related Questions