Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
iron-session
Advanced tools
The iron-session npm package is a lightweight and secure way to manage sessions in a Node.js application. It uses encryption to store session data in cookies, ensuring that the data is both secure and tamper-proof.
Create a session
This code demonstrates how to create a session and store user data in it. The session data is encrypted and stored in a cookie.
const { withIronSession } = require('iron-session/next');
const handler = async (req, res) => {
req.session.set('user', { id: 1, admin: true });
await req.session.save();
res.send('Session created');
};
module.exports = withIronSession(handler, {
password: process.env.SECRET_COOKIE_PASSWORD,
cookieName: 'myapp_cookiename',
cookieOptions: {
secure: process.env.NODE_ENV === 'production',
},
});
Retrieve session data
This code demonstrates how to retrieve session data. It checks if a user session exists and sends the user data in the response.
const { withIronSession } = require('iron-session/next');
const handler = async (req, res) => {
const user = req.session.get('user');
if (user) {
res.send(`User ID: ${user.id}, Admin: ${user.admin}`);
} else {
res.send('No user session found');
}
};
module.exports = withIronSession(handler, {
password: process.env.SECRET_COOKIE_PASSWORD,
cookieName: 'myapp_cookiename',
cookieOptions: {
secure: process.env.NODE_ENV === 'production',
},
});
Destroy a session
This code demonstrates how to destroy a session. It removes the session data from the cookie.
const { withIronSession } = require('iron-session/next');
const handler = async (req, res) => {
req.session.destroy();
res.send('Session destroyed');
};
module.exports = withIronSession(handler, {
password: process.env.SECRET_COOKIE_PASSWORD,
cookieName: 'myapp_cookiename',
cookieOptions: {
secure: process.env.NODE_ENV === 'production',
},
});
express-session is a popular session middleware for Express applications. It stores session data on the server-side, which can be more secure but requires additional storage management. Unlike iron-session, it does not encrypt session data by default.
cookie-session is another middleware for Express that stores session data in cookies. It is similar to iron-session in that it keeps session data client-side, but it does not provide built-in encryption, making it less secure out of the box.
client-sessions is a middleware that stores session data in cookies with optional encryption. It is similar to iron-session in terms of functionality but offers more configuration options for cookie storage and encryption.
iron-session
is a secure, stateless, and cookie-based session library for JavaScript.
Clerk is a complete suite of embeddable UIs, flexible APIs, and admin dashboards to authenticate and manage your users.
The session data is stored in signed and encrypted cookies which are decoded by your server code in a stateless fashion (= no network involved). This is the same technique used by frameworks like Ruby On Rails.
Online demo and examples: https://get-iron-session.vercel.app 👀
Featured in the Next.js documentation ⭐️
getIronSession<T>(req, res, sessionOptions): Promise<IronSession<T>>
getIronSession<T>(cookieStore, sessionOptions): Promise<IronSession<T>>
session.save(): Promise<void>
session.destroy(): void
session.updateConfig(sessionOptions: SessionOptions): void
sealData(data: unknown, { password, ttl }): Promise<string>
unsealData<T>(seal: string, { password, ttl }): Promise<T>
pnpm add iron-session
We have extensive examples here too: https://get-iron-session.vercel.app/.
To get a session, there's a single method to know: getIronSession
.
// Next.js API Routes and Node.js/Express/Connect.
import { getIronSession } from 'iron-session';
export async function get(req, res) {
const session = await getIronSession(req, res, { password: "...", cookieName: "..." });
return session;
}
export async function post(req, res) {
const session = await getIronSession(req, res, { password: "...", cookieName: "..." });
session.username = "Alison";
await session.save();
}
// Next.js Route Handlers (App Router)
import { cookies } from 'next/headers';
import { getIronSession } from 'iron-session';
export async function GET() {
const session = await getIronSession(cookies(), { password: "...", cookieName: "..." });
return session;
}
export async function POST() {
const session = await getIronSession(cookies(), { password: "...", cookieName: "..." });
session.username = "Alison";
await session.save();
}
// Next.js Server Components and Server Actions (App Router)
import { cookies } from 'next/headers';
import { getIronSession } from 'iron-session';
async function getIronSessionData() {
const session = await getIronSession(cookies(), { password: "...", cookieName: "..." });
return session
}
async function Profile() {
const session = await getIronSessionData();
return <div>{session.username}</div>;
}
We have many different patterns and examples on the online demo, have a look: https://get-iron-session.vercel.app/.
✅ Production ready and maintained.
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 object
with incrementing keys like this: {2: "...", 1: "..."}
to allow for password rotation. iron-session will use the highest numbered key for new cookies.
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.
cookieOptions
, optional: Any option available from jshttp/cookie#serialize except for encode
which is not a Set-Cookie Attribute. See Mozilla Set-Cookie Attributes and Chrome Cookie Fields. Default to:
{
httpOnly: true,
secure: true, // set this to false in local (non-HTTPS) development
sameSite: "lax",// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#lax
maxAge: (ttl === 0 ? 2147483647 : ttl) - 60, // Expire cookie before the session expires.
path: "/",
}
getIronSession<T>(req, res, sessionOptions): Promise<IronSession<T>>
type SessionData = {
// Your data
}
const session = await getIronSession<SessionData>(req, res, sessionOptions);
getIronSession<T>(cookieStore, sessionOptions): Promise<IronSession<T>>
type SessionData = {
// Your data
}
const session = await getIronSession<SessionData>(cookies(), sessionOptions);
session.save(): Promise<void>
Saves the session. This is an asynchronous operation. It must be done and awaited before headers are sent to the client.
await session.save()
session.destroy(): void
Destroys the session. This is a synchronous operation as it only removes the cookie. It must be done before headers are sent to the client.
session.destroy()
session.updateConfig(sessionOptions: SessionOptions): void
Updates the configuration of the session with new session options. You still need to call save() if you want them to be applied.
sealData(data: unknown, { password, ttl }): Promise<string>
This is the underlying method and seal mechanism that powers iron-session
. You can use it to seal any data
you want and pass it around. One usecase are magic links: you generate a seal that contains a user id to login and send it to a route on your website (like /magic-login
). Once received, you can safely decode the seal with unsealData
and log the user in.
unsealData<T>(seal: string, { password, ttl }): Promise<T>
This is the opposite of sealData
and allow you to decode a seal to get the original data back.
This makes your sessions stateless: since the data is passed around in cookies, you do not need any server or service to store session data.
More information can also be found on the Ruby On Rails website which uses the same technique.
Sessions cannot be instantly invalidated (or "disconnect this customer") as there is typically no state stored about sessions on the server by default. However, in most applications, the first step upon receiving an authenticated request is to validate the user and their permissions in the database. So, to easily disconnect customers (or invalidate sessions), you can add an `isBlocked`` state in the database and create a UI to block customers.
Then, every time a request is received that involves reading or altering sensitive data, make sure to check this flag.
Yes, we expose sealData
and unsealData
which are not tied to cookies. This way you can seal and unseal any object in your application and move seals around to login users.
Not so much:
Depending on your own needs and preferences, iron-session
may or may not fit you.
@hapi/iron
.@hapi/iron
as
iron-webcrypto
using standard
web APIs.next-connect
and
next-session
.FAQs
Secure, stateless, and cookie-based session library for JavaScript
The npm package iron-session receives a total of 140,287 weekly downloads. As such, iron-session popularity was classified as popular.
We found that iron-session demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.