Skip to content

Instantly share code, notes, and snippets.

@jadaradix
Created June 16, 2017 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jadaradix/500f5d1fc829117b6592dc92f319d13f to your computer and use it in GitHub Desktop.
Save jadaradix/500f5d1fc829117b6592dc92f319d13f to your computer and use it in GitHub Desktop.
hapi-dynamic-cors.js
const Hapi = require('hapi');
const allowedOrigins = [];
const middleware = function addCorsHeaders (request, reply) {
// not cors
if (!request.headers.origin) {
return reply.continue()
}
// depending on whether we have a boom or not,
// headers need to be set differently.
var response = request.response.isBoom ? request.response.output : request.response
// this is the important bit
if (allowedOrigins.includes(request.headers.origin)) {
response.headers['access-control-allow-origin'] = request.headers.origin
}
response.headers['access-control-allow-credentials'] = 'true'
if (request.method !== 'options') {
return reply.continue()
}
response.statusCode = 200
response.headers['access-control-expose-headers'] = 'content-type, content-length, etag'
response.headers['access-control-max-age'] = 60 * 10 // 10 minutes
// dynamically set allowed headers & method
if (request.headers['access-control-request-headers']) {
response.headers['access-control-allow-headers'] = request.headers['access-control-request-headers']
}
if (request.headers['access-control-request-method']) {
response.headers['access-control-allow-methods'] = request.headers['access-control-request-method']
}
reply.continue()
}
// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 5678
});
// load middleware
server.ext('onPreResponse', middleware);
server.route({
method: 'GET',
path:'/hello',
handler: function (request, reply) {
return reply('hello world');
}
});
// Start the server
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
console.log('in 10 seconds, http://127.0.0.1:8765 will be allowed');
setTimeout(() => {
console.log('allowed http://127.0.0.1:8765');
allowedOrigins.push('http://127.0.0.1:8765');
}, 10 * 1000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment