NuxtN
Nuxt14mo ago
Will

How-to set a response header in the server route

I'd like to know how to explicitly set a header in response to a server route. Specifically, I'd like to set the Content-Type of the returned data.

This question specifically relates to /server routes.

I understand it's possible to set the HTTP response status code using setResponseStatus(event, 202). However, I can't find any details on setting the response headers.

For example, I have some code that generates a sitemap and returns this as a promise-wrapped buffer. Or some code that generates dynamic images and returns these also as a buffer...

export default defineEventHandler(async (event) => {
  // Build sitemap - e.g. using node-sitemap
  const sitemap = new SitemapStream({
    hostname: FRONTEND_URL,
    xmlns: {
      xhtml: true,
      image: true,
      video: true,
      custom: [
        'xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"',
        'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"',
      ],
    }
  })

  // Fetch all documents
  const projects = await fetchProjects();
  const docsPages = await fetchDocsPages(projects);

  // Write pages
  writeHomepage(sitemap);
  writeProjects(projects, sitemap);
  writeDocs(projects, docsPages, sitemap);
  writeSpecialPages(sitemap);

  sitemap.end()

  return streamToPromise(sitemap);
})


This returns the buffered sitemap text! Great - but there's no content-type set, meaning the browser has to implicitly infer its type. That's fine, but in my use case, a website I supply sitemaps too via a hook neccessitates the content type being explicitly set in the response header. Similarly, another needs those images to have an implicitly-set content-type header to be displayed correctly.
Was this page helpful?