All Projects → vvo → iron-session

vvo / iron-session

Licence: MIT license
🛠 Node.js stateless session utility using signed and encrypted cookies to store data. Works with Next.js, Express, NestJs, Fastify, and any Node.js HTTP framework.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to iron-session

Node Rate Limiter Flexible
Node.js rate limit requests by key with atomic increments in single process or distributed environment.
Stars: ✭ 1,950 (+12.78%)
Mutual labels:  auth, nestjs
nestjs-cookie-session
Idiomatic Cookie Session Module for NestJS. Built on top of `cookie-session` 😻
Stars: ✭ 35 (-97.98%)
Mutual labels:  session, nestjs
Api
🏁🛠️ SaaS backend & API framework based on @nestjs
Stars: ✭ 390 (-77.44%)
Mutual labels:  auth, nestjs
next-api-decorators
Collection of decorators to create typed Next.js API routes, with easy request validation and transformation.
Stars: ✭ 187 (-89.18%)
Mutual labels:  next, nestjs
hutplate
A Go library over standard net/http library with auth, session, err handling and more.
Stars: ✭ 28 (-98.38%)
Mutual labels:  session, auth
Hzdtf.foundation.framework
基础框架系统,支持.NET和.NET Core平台,语言:C#,DB支持MySql和SqlServer,主要功能有抽象持久化、服务层,将业务基本的增删改查抽离复用;提供代码生成器从DB生成实体、持久化、服务以及MVC控制器,每层依赖接口,并需要在客户端将对应实现层用Autofac程序集依赖注入,用AOP提供日志跟踪、事务、模型验证等。对Autofac、Redis、RabbitMQ封装扩展;DB访问提供自动主从访问,Redis客户端分区。特别适合管理系统。
Stars: ✭ 22 (-98.73%)
Mutual labels:  cookies, auth
OSAPI
👋 OSAPI 是依靠通用性后台管理平台搭建的API管理平台,基于 vue3、Nestjs 技术栈实现,包含 RBAC 角色权限模块、数据展示、编辑等模块。
Stars: ✭ 32 (-98.15%)
Mutual labels:  session, nestjs
firebase-spring-boot-rest-api-authentication
Firebase Spring Boot Rest API Authentication
Stars: ✭ 172 (-90.05%)
Mutual labels:  cookies, session
Sessionup
Straightforward HTTP session management
Stars: ✭ 107 (-93.81%)
Mutual labels:  cookies, session
Authenticationintro
Stars: ✭ 82 (-95.26%)
Mutual labels:  cookies, session
rust cms
使用Rust编写一个CMS(内容管理系统)可以做为个人博客,公司网站
Stars: ✭ 32 (-98.15%)
Mutual labels:  session, auth
nestjs-session
Idiomatic Session Module for NestJS. Built on top of `express-session` 😎
Stars: ✭ 150 (-91.32%)
Mutual labels:  session, nestjs
next-size
Next.js plugin to print browser assets sizes
Stars: ✭ 39 (-97.74%)
Mutual labels:  next
stack
🥭 nxpm-stack lets you generate a complete and opinionated full-stack application in a Nx Workspace, ready to extend and deploy!
Stars: ✭ 98 (-94.33%)
Mutual labels:  nestjs
nestjs-i18n
The i18n module for nestjs.
Stars: ✭ 376 (-78.25%)
Mutual labels:  nestjs
app
Aplus Framework App Project
Stars: ✭ 338 (-80.45%)
Mutual labels:  session
nest-abstract
NestJs Abstraction Helper
Stars: ✭ 36 (-97.92%)
Mutual labels:  nestjs
is-even
SaaS platform for checking if number is even
Stars: ✭ 66 (-96.18%)
Mutual labels:  nestjs
nest-keycloak-connect
keycloak-nodejs-connect module for Nest
Stars: ✭ 174 (-89.94%)
Mutual labels:  nestjs
nestjs-rest-sample
NestJS RESTful APIs Sample
Stars: ✭ 204 (-88.2%)
Mutual labels:  nestjs

iron-session GitHub license Tests npm Downloads

⭐️ Featured in the Next.js documentation

🛠 Node.js stateless session utility using signed and encrypted cookies to store data. Works with Next.js, Express, NestJs, Fastify, and any Node.js HTTP framework.

The session data is stored in encrypted cookies ("seals"). And only your server can decode the session data. There are no session ids, making iron sessions "stateless" from the server point of view.

This strategy of storing session data is the same technique used by frameworks like Ruby On Rails (their default strategy).

The underlying cryptography library is iron which was created by the lead developer of OAuth 2.0.

Online demo: https://iron-session-example.vercel.app 👀


Table of contents:

Installation

npm add iron-session

Usage (Next.js)

You can find full featured examples (Next.js, Express) in the examples folder.

The password is a private key you must pass at runtime and builtime (for getServerSideProps), it has to be at least 32 characters long. You can use https://1password.com/password-generator/ to generate strong passwords.

Session duration is 14 days by default, check the API docs for more info.

⚠️ Always store passwords in encrypted environment variables on your platform. Vercel does this automatically.

Login API Route:

// pages/api/login.ts

import { withIronSessionApiRoute } from "iron-session/next";

export default withIronSessionApiRoute(
  async function loginRoute(req, res) {
    // get user from database then:
    req.session.user = {
      id: 230,
      admin: true,
    };
    await req.session.save();
    res.send({ ok: true });
  },
  {
    cookieName: "myapp_cookiename",
    password: "complex_password_at_least_32_characters_long",
    // secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
    cookieOptions: {
      secure: process.env.NODE_ENV === "production",
    },
  },
);

User API Route:

// pages/api/user.ts

import { withIronSessionApiRoute } from "iron-session/next";

export default withIronSessionApiRoute(
  function userRoute(req, res) {
    res.send({ user: req.session.user });
  },
  {
    cookieName: "myapp_cookiename",
    password: "complex_password_at_least_32_characters_long",
    // secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
    cookieOptions: {
      secure: process.env.NODE_ENV === "production",
    },
  },
);

Logout Route:

// pages/api/logout.ts

import { withIronSessionApiRoute } from "iron-session/next";

export default withIronSessionApiRoute(
  function logoutRoute(req, res, session) {
    req.session.destroy();
    res.send({ ok: true });
  },
  {
    cookieName: "myapp_cookiename",
    password: "complex_password_at_least_32_characters_long",
    // secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
    cookieOptions: {
      secure: process.env.NODE_ENV === "production",
    },
  },
);

getServerSideProps:

// pages/admin.tsx

import { withIronSessionSsr } from "iron-session/next";

export const getServerSideProps = withIronSessionSsr(
  async function getServerSideProps({ req }) {
    const user = req.session.user;

    if (user.admin !== true) {
      return {
        notFound: true,
      };
    }

    return {
      props: {
        user: req.session.user,
      },
    };
  },
  {
    cookieName: "myapp_cookiename",
    password: "complex_password_at_least_32_characters_long",
    // secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
    cookieOptions: {
      secure: process.env.NODE_ENV === "production",
    },
  },
);

Note: We encourage you to create a withSession utility so you do not have to repeat the password and cookie name in every route. You can see how to do that in the example.

Advanced usage

Coding best practices

Here's an example Login API route that is easier to read because of less nesting:

// pages/api/login.ts

import { withIronSessionApiRoute } from "iron-session/next";
import { ironOptions } from "lib/config";

export default withIronSessionApiRoute(loginRoute, ironOptions);

async function loginRoute(req, res) {
  // get user from database then:
  req.session.user = {
    id: 230,
    admin: true,
  };
  await req.session.save();
  res.send({ ok: true });
}
// lib/config.ts

export const ironOptions = {
  cookieName: "myapp_cookiename",
  password: "complex_password_at_least_32_characters_long",
  // secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
  cookieOptions: {
    secure: process.env.NODE_ENV === "production",
  },
};

Session wrappers

If you do not want to pass down the password and cookie name in every API route file or page then you can create wrappers like this:

JavaScript:

// lib/withSession.js

import { withIronSessionApiRoute, withIronSessionSsr } from "iron-session/next";

const sessionOptions = {
  password: "complex_password_at_least_32_characters_long",
  cookieName: "myapp_cookiename",
  // secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
  cookieOptions: {
    secure: process.env.NODE_ENV === "production",
  },
};

export function withSessionRoute(handler) {
  return withIronSessionApiRoute(handler, sessionOptions);
}

export function withSessionSsr(handler) {
  return withIronSessionSsr(handler, sessionOptions);
}

TypeScript:

// lib/withSession.ts

import { withIronSessionApiRoute, withIronSessionSsr } from "iron-session/next";
import {
  GetServerSidePropsContext,
  GetServerSidePropsResult,
  NextApiHandler,
} from "next";

const sessionOptions = {
  password: "complex_password_at_least_32_characters_long",
  cookieName: "myapp_cookiename",
  // secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
  cookieOptions: {
    secure: process.env.NODE_ENV === "production",
  },
};

export function withSessionRoute(handler: NextApiHandler) {
  return withIronSessionApiRoute(handler, sessionOptions);
}

// Theses types are compatible with InferGetStaticPropsType https://nextjs.org/docs/basic-features/data-fetching#typescript-use-getstaticprops
export function withSessionSsr<
  P extends { [key: string]: unknown } = { [key: string]: unknown },
>(
  handler: (
    context: GetServerSidePropsContext,
  ) => GetServerSidePropsResult<P> | Promise<GetServerSidePropsResult<P>>,
) {
  return withIronSessionSsr(handler, sessionOptions);
}

Usage in API Routes:

// pages/api/login.ts

import { withSessionRoute } from "lib/withSession";

export default withSessionRoute(loginRoute);

async function loginRoute(req, res) {
  // get user from database then:
  req.session.user = {
    id: 230,
    admin: true,
  };
  await req.session.save();
  res.send("Logged in");
}

Usage in getServerSideProps:

// pages/admin.tsx

import { withSessionSsr } from "lib/withSession";

export const getServerSideProps = withSessionSsr(
  async function getServerSideProps({ req }) {
    const user = req.session.user;

    if (user.admin !== true) {
      return {
        notFound: true,
      };
    }

    return {
      props: {
        user: req.session.user,
      },
    };
  },
);

Typing session data with TypeScript

req.session is automatically populated with the right types so .save() and .destroy() can be called on it.

But you might want to go further and type your session data also. To do so, use module augmentation:

declare module "iron-session" {
  interface IronSessionData {
    user?: {
      id: number;
      admin?: boolean;
    };
  }
}

You can put this code anywhere in your project, as long as it is in a file that will be required at some point. For example it could be inside your lib/withSession.ts wrapper or inside an additional.d.ts if you're using Next.js.

We've taken this technique from express-session types. If you have any comment on

Express

See examples/express for an example of how to use this with Express.

Handle password rotation/update the password

When you want to:

  • rotate passwords for better security every two (or more, or less) weeks
  • change the password you previously used because it leaked somewhere (😱)

Then you can use multiple passwords:

Week 1:

withIronSessionApiRoute(handler, {
  password: {
    1: "complex_password_at_least_32_characters_long",
  },
});

Week 2:

withIronSessionApiRoute(handler, {
  password: {
    2: "another_password_at_least_32_characters_long",
    1: "complex_password_at_least_32_characters_long",
  },
});

Notes:

  • The password used to encrypt session data (to seal) is always the highest number found in the map (2 in the example).
  • The passwords used to decrypt session data are all passwords in the map (this is how rotation works).
  • Even if you do not provide a list at first, you can always move to multiple passwords afterwards. The first password you've used has a default id of 1.

Magic links

Because of the stateless nature of iron-session, it's very easy to implement patterns like magic links. For example, you might want to send an email to the user with a link to a page where they will be automatically logged in. Or you might want to send a Slack message to someone with a link to your application where they will be automatically logged in.

Here's how to implement that:

Send an email with a magic link to the user:

// pages/api/sendEmail.ts

import { sealData } from "iron-session";

export default async function sendEmailRoute(req, res) {
  const user = getUserFromDatabase(req.query.userId);

  const seal = await sealData(
    {
      userId: user.id,
    },
    {
      password: "complex_password_at_least_32_characters_long",
    },
  );

  await sendEmail(
    user.email,
    "Magic link",
    `Hey there ${user.name}, <a href="https://myapp.com/api/magicLogin?seal=${seal}">click here to login</a>.`,
  );

  res.send({ ok: true });
}

The default ttl for such seals is 14 days. To specify a ttl, provide it in seconds like so:

const fifteenMinutesInSeconds = 15 * 60;

const seal = await sealData(
  {
    userId: user.id,
  },
  {
    password: "complex_password_at_least_32_characters_long",
    ttl: fifteenMinutesInSeconds,
  },
);

Login the user automatically and redirect:

// pages/api/magicLogin.ts

import { unsealData } from "iron-session";
import { withIronSessionApiRoute } from "iron-session/next";

export default withIronSessionApiRoute(magicLoginRoute, {
  cookieName: "myapp_cookiename",
  password: "complex_password_at_least_32_characters_long",
  cookieOptions: {
    secure: process.env.NODE_ENV === "production",
  },
});

async function magicLoginRoute(req, res) {
  const { userId } = await unsealData(req.query.seal, {
    password: "complex_password_at_least_32_characters_long",
  });

  const user = getUserFromDatabase(userId);

  req.session.user = {
    id: user.id,
  };

  await req.session.save();

  res.redirect(`/dashboard`);
}

You might want to include error handling in the API routes. For example checking if req.session.user is already defined in login or handling bad seals.

Impersonation, login as someone else

You may want to impersonate your own users, to check how they see your application. This can be extremely useful. For example you could have a page that list all your users and with links you can click to impersonate them.

Login as someone else:

// pages/api/impersonate.ts

import { withIronSessionApiRoute } from "iron-session/next";

export default withIronSessionApiRoute(impersonateRoute, {
  cookieName: "myapp_cookiename",
  password: "complex_password_at_least_32_characters_long",
  cookieOptions: {
    secure: process.env.NODE_ENV === "production",
  },
});

async function impersonateRoute(req, res) {
  if (!req.session.isAdmin) {
    // let's pretend this route does not exists if user is not an admin
    return res.status(404).end();
  }

  req.session.originalUser = req.session.originalUser || req.session.user;
  req.session.user = {
    id: req.query.userId,
  };
  await req.session.save();
  res.redirect("/dashboard");
}

Stop impersonation:

// pages/api/stopImpersonate.ts

import { withIronSessionApiRoute } from "iron-session/next";

export default withIronSessionApiRoute(stopImpersonateRoute, {
  cookieName: "myapp_cookiename",
  password: "complex_password_at_least_32_characters_long",
  cookieOptions: {
    secure: process.env.NODE_ENV === "production",
  },
});

async function stopImpersonateRoute(req, res) {
  if (!req.session.isAdmin) {
    // let's pretend this route does not exists if user is not an admin
    return res.status(404).end();
  }

  req.session.user = req.session.originalUser;
  delete req.session.originalUser;
  await req.session.save();
  res.redirect("/dashboard");
}

Session cookies

If you want cookies to expire when the user closes the browser, pass maxAge: undefined in cookie options, this way:

// pages/api/user.ts

import { withIronSessionApiRoute } from "iron-session/next";

export default withIronSessionApiRoute(
  function userRoute(req, res) {
    res.send({ user: req.session.user });
  },
  {
    cookieName: "myapp_cookiename",
    password: "complex_password_at_least_32_characters_long",
    cookieOptions: {
      maxAge: undefined,
      secure: process.env.NODE_ENV === "production",
    },
  },
);

Beware, modern browsers might not delete cookies at all using this technique because of session restoring.

Firebase usage

This library can be used with Firebase, as long as you set the cookie name to __session which seems to be the only valid cookie name there.

API

ironOptions

Only two options are required: password and cookieName. Everything else is automatically computed and usually doesn't need to be changed.

  • password, required: Private key used to encrypt the cookie. It has to be at least 32 characters long. Use https://1password.com/password-generator/ to generate strong passwords. password can be either a string or an array of objects like this: [{id: 2, password: "..."}, {id: 1, password: "..."}] to allow for password rotation.
  • cookieName, required: Name of the cookie to be stored
  • ttl, optional: In seconds. Default to the equivalent of 14 days. You can set this to 0 and iron-session will compute the maximum allowed value by cookies (~70 years).
  • cookieOptions, optional: Any option available from jshttp/cookie#serialize. Default to:
{
  httpOnly: true,
  secure: true, // true when using https, false otherwise
  sameSite: "lax", // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#lax
  // The next line makes sure browser will expire cookies before seals are considered expired by the server. It also allows for clock difference of 60 seconds maximum between servers and clients.
  maxAge: (ttl === 0 ? 2147483647 : ttl) - 60,
  path: "/",
  // other options:
  // domain, if you want the cookie to be valid for the whole domain and subdomains, use domain: example.com
  // encode, there should be no need to use this option, encoding is done by iron-session already
  // expires, there should be no need to use this option, maxAge takes precedence
}

Next.js: withIronSessionApiRoute(handler, ironOptions | (req: NextApiRequest, res: NextApiResponse) => IronOptions | Promise<IronOptions>)

Wraps a Next.js API Route and adds a session object to the request.

import { withIronSessionApiRoute } from "iron-session/next";

export default withIronSessionApiRoute(
  function userRoute(req, res) {
    res.send({ user: req.session.user });
  },
  {
    cookieName: "myapp_cookiename",
    password: "complex_password_at_least_32_characters_long",
    // secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
    cookieOptions: {
      secure: process.env.NODE_ENV === "production",
    },
  },
);

// You can also pass an async or sync function which takes request and response object and return IronSessionOptions
export default withIronSessionApiRoute(
  function userRoute(req, res) {
    res.send({ user: req.session.user });
  },
  (req, res) => {
    // Infer max cookie from request
    const maxCookieAge = getMaxCookieAge(req);
    return {
      cookieName: "myapp_cookiename",
      password: "complex_password_at_least_32_characters_long",
      // secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
      cookieOptions: {
        // setMaxCookie age here.
        maxCookieAge,
        secure: process.env.NODE_ENV === "production",
      },
    };
  },
);

Next.js: withIronSessionSsr(handler, ironOptions | (req: IncomingMessage, res: ServerResponse) => IronOptions | Promise<IronOptions>)

Wraps a Next.js getServerSideProps and adds a session object to the request of the context.

import { withIronSessionSsr } from "iron-session/next";

export const getServerSideProps = withIronSessionSsr(
  async function getServerSideProps({ req }) {
    return {
      props: {
        user: req.session.user,
      },
    };
  },
  {
    cookieName: "myapp_cookiename",
    password: "complex_password_at_least_32_characters_long",
    // secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
    cookieOptions: {
      secure: process.env.NODE_ENV === "production",
    },
  },
);

// You can also pass an async or sync function which takes request and response object and return IronSessionOptions
export const getServerSideProps = withIronSessionSsr(
  async function getServerSideProps({ req }) {
    return {
      props: {
        user: req.session.user,
      },
    };
  },
  (req, res) => {
    return {
      cookieName: "myapp_cookiename",
      password: "complex_password_at_least_32_characters_long",
      // secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
      cookieOptions: {
        secure: process.env.NODE_ENV === "production",
      },
    };
  },
);

Express: ironSession(ironOptions)

Creates an express middleware that adds a session object to the request.

import { ironSession } from "iron-session/express";

app.use(ironSession(ironOptions));

session.save()

Saves the session and sets the cookie header to be sent once the response is sent.

await req.session.save();

session.destroy()

Empties the session object and sets the cookie header to be sent once the response is sent. The browser will then remove the cookie automatically.

You don't have to call req.session.save() after calling req.session.destroy(). The session is saved automatically.

FAQ

Why use pure cookies for sessions?

This makes your sessions stateless: you do not have to store session data on your server. You do not need another server or service to store session data. This is particularly useful in serverless architectures where you're trying to reduce your backend dependencies.

What are the drawbacks?

There are some drawbacks to this approach:

  • you cannot invalidate a seal when needed because there's no state stored on the server-side about them. We consider that the way the cookie is stored reduces the possibility for this eventuality to happen. Also, in most applications the first thing you do when receiving an authenticated request is to validate the user and their rights in your database, which defeats the case where someone would try to use a token while their account was deactivated/deleted. Now if someone steals a user token you should have a process in place to mitigate that: deactivate the user and force a re-login with a flag in your database for example.
  • application not supporting cookies won't work, but you can use iron-store to implement something similar. In the future, we could allow iron-session to accept basic auth or bearer token methods too. Open an issue if you're interested.
  • on most browsers, you're limited to 4,096 bytes per cookie. To give you an idea, an iron-session cookie containing {user: {id: 100}} is 265 bytes signed and encrypted: still plenty of available cookie space in here.
  • performance: crypto on the server-side could be slow, if that's the case let me know. Also, cookies are sent to every request to your website, even images, so this could be an issue

Now that you know the drawbacks, you can decide if they are an issue for your application or not. More information can also be found on the Ruby On Rails website which uses the same technique.

How is this different from JWT?

Not so much:

  • JWT is a standard, it stores metadata in the JWT token themselves to ensure communication between different systems is flawless.
  • JWT tokens are not encrypted, the payload is visible by customers if they manage to inspect the seal. You would have to use JWE to achieve the same.
  • @hapi/iron mechanism is not a standard, it's a way to sign and encrypt data into seals

Depending on your own needs and preferences, iron-session may or may not fit you.

Project status

Production ready and maintained.

Credits

Thanks to Hoang Vo for advice and guidance while building this module. Hoang built next-connect and next-session.

Thanks to hapi team for creating iron.

References

Contributors

Thanks goes to these wonderful people (emoji key):


John Vandivier

💻 🤔 💡

searchableguy

⚠️ 📖 💻

This project follows the all-contributors specification. Contributions of any kind welcome!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].