Skip to content

Commit

Permalink
fix(storage-vercel-blob): return 404 when file is not found (#10327)
Browse files Browse the repository at this point in the history
### What

The vercel storage adapter returns a 500 internal server error when a
file is not found.
It's expected that it will return 404 when a file is not found.

### Why

The `head` function from vercel blob sdk does not return undefined when
a blob is not found, but throws an error as documented here:
https://vercel.com/docs/storage/vercel-blob/using-blob-sdk#head

### How

Check if exception thrown is of type BlobNotFoundError and return a 404
in that case.

### Testing

***Note***: I have not been able to test this inside payload itself as
I'm unable to build a package to test with. I have tested the
implementation outside. Is it possible to get a canary build so proper
testing with package can be done?

Fixes #10326
  • Loading branch information
andershermansen authored Jan 3, 2025
1 parent 1f4790a commit d68a1ea
Showing 1 changed file with 4 additions and 5 deletions.
9 changes: 4 additions & 5 deletions packages/storage-vercel-blob/src/staticHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { StaticHandler } from '@payloadcms/plugin-cloud-storage/types'
import type { CollectionConfig } from 'payload'

import { getFilePrefix } from '@payloadcms/plugin-cloud-storage/utilities'
import { head } from '@vercel/blob'
import { BlobNotFoundError, head } from '@vercel/blob'
import path from 'path'

type StaticHandlerArgs = {
Expand All @@ -24,10 +24,6 @@ export const getStaticHandler = (
const etagFromHeaders = req.headers.get('etag') || req.headers.get('if-none-match')

const blobMetadata = await head(fileUrl, { token })
if (!blobMetadata) {
return new Response(null, { status: 404, statusText: 'Not Found' })
}

const uploadedAtString = blobMetadata.uploadedAt.toISOString()
const ETag = `"${fileKey}-${uploadedAtString}"`

Expand Down Expand Up @@ -70,6 +66,9 @@ export const getStaticHandler = (
status: 200,
})
} catch (err: unknown) {
if (err instanceof BlobNotFoundError) {
return new Response(null, { status: 404, statusText: 'Not Found' })
}
req.payload.logger.error({ err, msg: 'Unexpected error in staticHandler' })
return new Response('Internal Server Error', { status: 500 })
}
Expand Down

0 comments on commit d68a1ea

Please sign in to comment.