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();
    }
});
Mr.Smithyyy
  • 2,157
  • 12
  • 49
  • 95

1 Answers1

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 ?

Karin C
  • 506
  • 1
  • 7
  • 18
mandaputtra
  • 922
  • 3
  • 18
  • 36
  • 2
    onSend seems to be more appropriate – Uzlopak Nov 22 '21 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: https://stackoverflow.com/a/74131067/4808079 – Seph Reed Oct 19 '22 at 20:09