0

I currently struggle with the following issue:

From an API-GET-Request I get an etag-Header I need to persist in the cache for a possible UPDATE?DELETE Request to be sent as If-Match-Header.

I try to save it in a Server-Side-Cookie like this:

// app/api/cart/[cartId]/route.ts
import { withApiAuthRequired } from '@auth0/nextjs-auth0';
import { NextResponse } from 'next/server';
import { createGlueServerClient } from '@/src/lib/http/client/client.glue.server';
import { cookies } from 'next/headers';

function setEtagFromResponse(response: Response) {
  const etag = response.headers.get('etag');
  if (etag) {
    cookies().set('etag', etag);
  }
}

const GET = withApiAuthRequired(async (request: Request, { params }: { params: { cartId: string } }) => {
  const client = createGlueServerClient();
  const response = await client.get(`carts/${params.cartId}`, {
    withAuth: true,
  });

  setEtagFromResponse(response);

  return NextResponse.json(await response.json());
});

export { GET };

But when I try to get it with cookies().get('etag').value in the PATCH-Request, it's just not there...

DotCoyote
  • 85
  • 2
  • 6

1 Answers1

1

A better approach would be to return the etag value in the GET response header. This way a client can read it from the response, and then use it in a subsequent PATCH / DELETE request. The cookies approach would be prone to race condition.

Igor Danchenko
  • 1,980
  • 1
  • 3
  • 13