SyntaxError: Unexpected token 'export' for Blob API

I’m trying to use a Blob, but when I fetch on my API, I get the error: SyntaxError: Unexpected token 'export' ??? My fetch function is (TSX file):

const handleUpload = async () => {
        const file = inputFileRef.current.files[0];

          const response = await fetch(`/api/upload?filename=${file.name}`,
            {
              method: 'POST',
              body: file,
            },
          );

          const newBlob = (await response.json()) as PutBlobResult;

          setBlob(newBlob);
    }

And the API is (js file):

import { put } from '@vercel/blob';
import { NextResponse } from 'next/server';

export async function POST(req) {
  const { searchParams } = new URL(req.url);
  const filename = searchParams.get('filename');

  // Here's the code for Pages API Routes:
  const blob = await put(filename, req, {
    access: 'public',
    token: process.env.BLOB_READ_WRITE_TOKEN
  });

  return NextResponse.json(blob);
}

// The next lines are required for Pages API Routes only
export const config = {
  api: {
    bodyParser: false,
  },
};

So the error is on export async function POST(req)
I don’t know how to solve it ???
Capture d'écran 2024-08-13 162343

Hi @mikalem898. There isn’t quite enough info here for anyone to say for sure what’s going wrong. Do you have a minimal reproducible example that we can use to help you with debugging?

Its difficult to make an example of a NextJs project…

Now I know that it is caused by:

import { NextResponse } from 'next/server';

bc when I try to remove it, I have not this error anymore, but another bc I cant use blob without this so ?

I did that, replace NextResponse by another way:

return res.json(blob)

But now, I have error TypeError: Invalid URL wich comes from URL(req.url) I mean ? but when logging it, its a valid URL: /api/upload?filename=file.png

So it’s bc of const { searchParams } = new URL(req.url); method, but how can I fix that ?

And when I try with ts file, I get TypeError: resolver is not a function, which is doesn’t used so that’s funny!!!

OKKKK its okkk ! I dont why the given code doesnt work for me but with some modifications I can run it !!
Modifs like adding the beginning of a valid URL hehe: new URL('https://localhost:3000/' + req.url);

1 Like

Thanks for coming back with your solution!

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.