2

For every route I have to type the same headers as shown below. Is there a way to set these headers globally so that they are used by default for every route and can be overridden on a per-route basis?

fastify.post("/api/users", async (request, reply) => {
    try {
        reply
            .code(200)
             header("Access-Control-Allow-Origin", "http://localhost:3000")
            .header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
            .header("Content-Type", "application/json; charset=utf-8")
            .send();
    } catch (error) {
        reply
            .code(400)
            .header("Access-Control-Allow-Origin", "http://localhost:3000")
            .header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
            .header("Content-Type", "application/json; charset=utf-8")
            .send();
    }
});

1 Answer 1

6

You can set some headers before use send()


fastify.addHook('preHandler', (req, repy, done) => {
  reply.header("key", "value")
  done()
})

fastify.post("api/users", async (req, reply) => {
  try {
    reply.code(200).send()
  } catch (err) {
    reply.code(400).send()
  }
})

But I saw you want to use CORS, why not use fastify-cors ?

2
  • 2
    onSend seems to be more appropriate
    – Uzlopak
    Nov 22, 2021 at 14:31
  • The reason not to use fastify-cors is that it's an entire package to learn and add to project, all to do something that should be easy and would be more valuable to learn in another way. I have an answer elsewhere that shows how to work with headers for cors: stackoverflow.com/a/74131067/4808079
    – Seph Reed
    Oct 19, 2022 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.