Skip to content

Instantly share code, notes, and snippets.

@FlameWolf
Created July 18, 2022 15:45
Show Gist options
  • Save FlameWolf/bf3d246800f7e910801af8cfecde8b98 to your computer and use it in GitHub Desktop.
Save FlameWolf/bf3d246800f7e910801af8cfecde8b98 to your computer and use it in GitHub Desktop.
Configure CORS in Fastify using onRequest hook
const server = fastify();
server.addHook("onRequest", async (request, reply) => {
reply.header("Access-Control-Allow-Origin", process.env.ALLOW_ORIGIN);
reply.header("Access-Control-Allow-Credentials", true);
reply.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept, X-Slug, X-UID");
reply.header("Access-Control-Allow-Methods", "OPTIONS, POST, PUT, PATCH, GET, DELETE");
if (request.method === "OPTIONS") {
reply.send();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment