I'm trying to upload a json file to Vercel Blob form server.
On the client:
import { upload } from '@vercel/blob/client';await upload(file.name, file, { access: 'public', handleUploadUrl: '/api/upload', clientPayload: fileId, });Server handler:
import { handleUpload, type HandleUploadBody } from '@vercel/blob/client';
export async function POST(request: NextRequest) { const session = await auth();
const userId = session?.user?.id;
if (!session || !session.user || !userId) { return new Response('Unauthorized', { status: 401 }); }
const body = (await request.json()) as HandleUploadBody;
const token = process.env.BLOB_READ_WRITE_TOKEN; console.log('BLOB_READ_WRITE_TOKEN ', { token });
try { const jsonResponse = await handleUpload({ token, request, body, onBeforeGenerateToken: async ( pathname: string, clientPayload: string | null ) => { if (!clientPayload) { throw new Error('Missing fileId'); }
await createImportData({ id: clientPayload, userId, createdAt: new Date(), });
console.log('File import data created: ', { clientPayload });
const validUntil = Math.floor(Date.now() / 1000) + 10 * 60; // 10 minutes return { allowedContentTypes: ['application/json'], validUntil, tokenPayload: JSON.stringify({ fileId: clientPayload, }), }; }, onUploadCompleted: async ({ blob, tokenPayload }) => { console.log('Blob upload completed'); const { fileId } = JSON.parse(tokenPayload || '{}');
try { processFileFromBlob(blob.downloadUrl, userId, fileId); } catch (error) { console.log('Error Processing the file: ', { fileId }); updateImportDataStatus({ id: fileId, status: 'error' }); throw error; } }, });
return NextResponse.json(jsonResponse); } catch (error) { console.error('Error processing file:', error); return NextResponse.json( { message: 'Error processing file' }, { status: 500 } ); }}The problem is that on the client i get wrong token and get 403 error.
Also, if i try to return my token from env manually like so:
return NextResponse.json({ ...jsonResponse, clientToken: token });
Then file uploads to Vercel Blob storage - i could even go and see it by returned url.
But then, method onUploadCompleted at the server doesn't evoke after file upload.
What i'm doing wrong?
Why handleUpload method from vercel returning wrong token and why my onUploadCompleted method doesn't work?>