Skip to content

Instantly share code, notes, and snippets.

@AndrewIngram
Created February 18, 2022 13:29
Show Gist options
  • Save AndrewIngram/eeecdea60fbf47e2e79eaf5be9ff5056 to your computer and use it in GitHub Desktop.
Save AndrewIngram/eeecdea60fbf47e2e79eaf5be9ff5056 to your computer and use it in GitHub Desktop.
next-runtime session middleware
import { json } from "next-runtime";
import jwt from "jsonwebtoken";
const SESSION_KEY = "some-secret";
export function readSession(cookies) {
const sessionCookie = cookies.get("session");
let data = {};
if (sessionCookie) {
data = jwt.verify(sessionCookie, SESSION_KEY);
delete data.iat;
}
return data;
}
export function writeSession(cookies, data) {
cookies.set("session", jwt.sign(data, SESSION_KEY));
}
export const session = async (ctx, next) => {
let data = readSession(ctx.cookies);
ctx.session = data;
try {
await next();
return json({ session: ctx.session });
} catch (err) {
throw err;
} finally {
// TODO dirty checks, to avoid unneccessary cookies
writeSession(ctx.cookies, ctx.session);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment