Search code examples
sveltesveltekit

can't set headers using setHeaders in /api/something/server.js


Could anyone explain how to set headers in api/something/+server.js in sveltekit?

I read the docs here

It's all about +page.server.js but not api/folder/+server.js

export async function POST(event){
  let newheader = {"potato" : "something"}

  //how to set headers?
  return new Response({success : true})
}

Solution

  • The response options object has a headers property. Also, if you want to return JSON, there is a static function Response.json that can be used. Otherwise you have to set the correct content type header and JSON stringify the value yourself.

    E.g.

    return Response.json(
        { success: true },
        {
            headers: {
                'potato': 'something',
            },
        },
    );
    

    If you just want to indicate a successful response, you don't need any response body.
    If you want to indicate an error, set status to something appropriate (e.g. 400 for bad request or 500 for server error).

    return new Response(null, { status: 400, headers: ... });