Skip to content

Instantly share code, notes, and snippets.

@ericmacfa ericmacfa/index.js
Last active Jul 3, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.