Skip to content

Instantly share code, notes, and snippets.

@smeijer
Forked from AndrewIngram/session.js
Created February 18, 2022 14:05
Show Gist options
  • Select an option

  • Save smeijer/7bbb87ec541435f3125000857337d280 to your computer and use it in GitHub Desktop.

Select an option

Save smeijer/7bbb87ec541435f3125000857337d280 to your computer and use it in GitHub Desktop.

Revisions

  1. @AndrewIngram AndrewIngram created this gist Feb 18, 2022.
    37 changes: 37 additions & 0 deletions session.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    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);
    }
    };