Next.js Discord

Discord Forum

CloudFront signed cookies with next/image

Unanswered
NoughtThought (he/him) posted this in #help-forum
Open in Discord
I'm using next/image to access images in an AWS S3 bucket. The S3 buckets are protected by CloudFront signed cookies.

I have an endpoint from out REST server that can send the cookies, either as JSON or on a Set-Cookie header. I can hit that endpoint from a server component and use next/headers's cookies.set() to set the cookies in the browser.

The first problem is the cookies.set() sets with cookies with the Next app's host domain (eg, localhost:3000 in local development), which doesn't match CloudFront/S3 bucket domain. But even in a staging deployment, which has a host that does match, we still have the problems below.

Rather than requesting the image from the S3 bucket directly, next/image makes the request to the Next.js server which, I'm guessing, then makes the request to the S3 bucket and then does its optimisation and caching magic before passing the image on to the browser.

I can see that the cookies are attached to the request that goes to the Next.js server has the cookies attached:

// Local
curl 'https://localhost:3000/_next/image?url=https%3A%2F%2Fcdn.example.com%2F20240809%2Fstory_6.jpg&w=256&q=75' \
  -H 'Cookie: CloudFront-Key-Pair-Id=[redacted]; CloudFront-Policy=[redacted]; CloudFront-Signature=[redacted]' \


// Preview
curl 'https://app-preview.example.com/_next/image?url=https%3A%2F%2Fcdn.example.com%2F20240811%2Fstory_0.jpg&w=256&q=75' \
  -H 'cookie: _vercel_jwt=[redacted]; CloudFront-Policy=[redacted]; CloudFront-Signature=[redacted]; CloudFront-Key-Pair-Id=[redacted]; CloudFront-Policy=[redacted]; \


Locally, the request returns a 403, the preview deployment request returns a 503 with "OPTIMIZED_EXTERNAL_IMAGE_REQUEST_UNAUTHORIZED" error message.

When the Next.js server makes the request to the S3 bucket, is the cookie header passed on to that request?

How can I make this work?

3 Replies

Also, if I add the unoptimized prop, the request is made directly to the S3 bucket, with the cookies attached, and the request is successful. So it's not a problem with the cookies themselves.
The first problem is the cookies.set() sets with cookies with the Next app's host domain (eg, localhost:3000 in local development),
...and I just realised that you can set a domain option on cookies.set(), but that doesn't solve the all the problems.
Also, I'm now using the -H option on yarn dev to use local.example.com as the hostname in local development.