Koa Session Comprehensive Guide for Web Developers to Master Session Management in KoaJS

Introduction to koa-session

koa-session is a session management middleware for Koa applications. It helps in handling user sessions seamlessly and securely in KoaJS applications. Below, we will discuss various APIs provided by koa-session along with practical code examples.

Installation

 npm install koa-session

Basic Usage

 
 const Koa = require('koa');
 const session = require('koa-session');

 const app = new Koa();
 app.keys = ['your-session-secret'];

 const CONFIG = {
   key: 'koa:sess', // cookie key (default is koa:sess)
   maxAge: 86400000, // cookie's max age in ms (1 day)
   autoCommit: true, // automatically commit headers (default is true)
   overwrite: true, // can overwrite or not (default true)
   httpOnly: true, // cookie is only available over HTTP(S), not JavaScript (default true)
   signed: true, // signed cookie (default true)
   rolling: false, // force a session identifier cookie to be set on every response (default is false)
   renew: false, // renew session when session is nearly expired, so we can always keep user logged in
   secure: false, // secure cookie (default false)
 };

 app.use(session(CONFIG, app));

 app.use(async ctx => {
   if (ctx.path === '/favicon.ico') return;

   let n = ctx.session.views || 0;
   ctx.session.views = ++n;
   ctx.body = `${n} views`;
 });

 app.listen(3000);
 

Advanced Configuration

 
 const advancedConfig = {
   key: 'koa.advanced:sess',
   maxAge: 3600000, // 1 hour
   autoCommit: true,
   overwrite: true,
   httpOnly: true,
   signed: true,
   rolling: true, // force a session identifier cookie to be set on every response
   secure: process.env.NODE_ENV === 'production', // secure cookie in production environment
 };

 app.use(session(advancedConfig, app));
 

Accessing Session Data

 
 app.use(async ctx => {
   if (ctx.session.isNew) {
     ctx.session.userId = '1234';
     ctx.session.role = 'admin';
   }

   ctx.body = `User ID: ${ctx.session.userId}, Role: ${ctx.session.role}`;
 });
 

Destroying a Session

 
 app.use(async ctx => {
   if (ctx.path === '/logout') {
     ctx.session = null;
     ctx.body = 'Session Destroyed';
   }
 });
 

Regenerating Session ID

 
 app.use(async ctx => {
   if (ctx.path === '/secure' && ctx.session.userId) {
     ctx.session.regenerateId();
     ctx.body = 'Session ID Regenerated';
   }
 });
 

Session Flash Messages

 
 app.use(async ctx => {
   if (ctx.path === '/flash') {
     ctx.session.flash = 'Flash Message Example';
     ctx.redirect('/');
   } else if (ctx.session.flash) {
     const message = ctx.session.flash;
     ctx.session.flash = null;
     ctx.body = message;
   } else {
     ctx.body = 'No Flash Message';
   }
 });
 

Complete Example

 
 const Koa = require('koa');
 const session = require('koa-session');
 const Router = require('@koa/router');

 const app = new Koa();
 const router = new Router();
 app.keys = ['your-session-secret'];

 const CONFIG = {
   key: 'koa:sess',
   maxAge: 86400000,
   autoCommit: true,
   overwrite: true,
   httpOnly: true,
   signed: true,
   rolling: false,
   renew: false,
   secure: process.env.NODE_ENV === 'production',
 };

 app.use(session(CONFIG, app));

 router.get('/', async ctx => {
   let n = ctx.session.views || 0;
   ctx.session.views = ++n;
   ctx.body = `${n} views`;
 });

 router.get('/set', async ctx => {
   ctx.session.userId = '1234';
   ctx.body = 'UserId set in session';
 });

 router.get('/get', async ctx => {
   ctx.body = `User ID: ${ctx.session.userId}`;
 });

 router.get('/logout', async ctx => {
   ctx.session = null;
   ctx.body = 'Session Destroyed';
 });

 router.get('/flash', async ctx => {
   ctx.session.flash = 'Flash Message Example';
   ctx.redirect('/');
 });

 router.get('/show-flash', async ctx => {
   const message = ctx.session.flash;
   ctx.session.flash = null;
   ctx.body = message || 'No Flash Message';
 });

 app.use(router.routes()).use(router.allowedMethods());

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

Hash: 413f33c850969d60654fd8a5da31afffbf2a3fd57a78b3cb260698a75254486b

Leave a Reply

Your email address will not be published. Required fields are marked *