How to set headers to all responses in koa.js?

by muriel.schmidt , in category: Javascript , 7 months ago

How to set headers to all responses in koa.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , 7 months ago

@muriel.schmidt 

In Koa.js, you can set headers to all responses using middleware. Here is an example of how you can set headers to all responses in Koa.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
const Koa = require('koa');
const app = new Koa();

// Middleware to set headers to all responses
app.use(async (ctx, next) => {
  // Set headers
  ctx.set('X-Content-Type-Options', 'nosniff');
  ctx.set('X-XSS-Protection', '1; mode=block');

  // Proceed to the next middleware
  await next();
});

// Route handler
app.use(async ctx => {
  ctx.body = 'Hello, World!';
});

// Start the server
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});


In the above example, the middleware function sets the headers X-Content-Type-Options and X-XSS-Protection to all responses. The next() function is called to proceed to the next middleware in the stack.


By using middleware to set headers to all responses, you can ensure that the headers are added consistently to all responses in your Koa.js application.