Skip to content

Instantly share code, notes, and snippets.

@ericmacfa
Last active July 3, 2019 14:49
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 ericmacfa/20f70db342c8aed7feea844a847975aa to your computer and use it in GitHub Desktop.
Save ericmacfa/20f70db342c8aed7feea844a847975aa to your computer and use it in GitHub Desktop.
fastify-session -- Request handler called even when response.redirect() is called in preHandler
const fastify = require('fastify')();
const fastifyCookie = require('fastify-cookie');
const fastifySession = require('fastify-session');
const MemoryStore = require('memorystore')(fastifySession);
const ms = require('ms');
// region Plugins =============================================================
fastify.register(fastifyCookie);
fastify.register(fastifySession, {
cookieName: 'id',
secret: 'a secret with minimum length of 32 characters',
sessionMaxAge: ms('15 minutes'),
cookie: {
maxAge: ms('15 minutes'),
secure: false,
httpOnly: false,
sameSite: true
},
store: new MemoryStore({
checkPeriod: ms('1 minute'),
ttl: ms('15 minutes')
})
});
// endregion Plugins ==========================================================
// region Routes ==============================================================
fastify.route({
method: 'GET',
path: '/',
// With this hook, the handler is still called
preHandler: async function(request, reply) {
console.log('GET / -> preHandler()');
reply.redirect('/login');
},
// With this hook, the handler is not called (as expected)
// preHandler: function(request, reply, next) {
// console.log('GET / -> preHandler()');
// reply.redirect('/login');
// },
handler: function(request, reply) {
console.log('GET / -> handler() !! This should never be shown !!');
reply.send({ hello: 'world' });
}
});
fastify.route({
method: 'GET',
path: '/login',
handler: function(request, reply) {
console.log('GET /login -> handler()');
reply.send('Please log in');
}
});
// endregion Routes ===========================================================
fastify.listen(3000, err => {
if (err) throw err;
const { port } = fastify.server.address();
console.log(`server listening on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment