Vercel Functions - Content-Type header in vercel.json not working

This is because by default response returns have a Content-Type set, so that overrides your top level content type. a default function response on Vercel returns text/plain you can always just make a custom response that’s just the base response + the json header like so

export class JsonResponse extends Response {
  constructor(body: any, init?: ResponseInit) {
    super(JSON.stringify(body), {
      ...init,
      headers: { ...init?.headers, "Content-Type": "application/json" },
    });
  }
}

This can replace it to

export function GET(request: Request) {
  return new JsonResponse({ hello: "world" });
}

this automatically handles encoding the input as JSON and setting the header, if all your responses are JSON this is probably the best approach

Also please forgive the sin of JS OOP it’s just the easiest way to do this nicely

It also allows for typing the function returns still as Response due to the extension

import { JsonResponse } from "../util";

export function GET(request: Request): Response {
  const name: string = new URL(request.url).searchParams.get("name") ?? "";
  return new JsonResponse({ message: `Hello ${name}!` });
}
2 Likes