Security News
pnpm 10.0.0 Blocks Lifecycle Scripts by Default
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
next-iron-session
Advanced tools
Next.js stateless session utility using signed and encrypted cookies to store data
🛠 Next.js and Express (connect middleware) stateless session utility using signed and encrypted cookies to store data
This Next.js, Express and Connect backend utility allows you to create a session to then be stored in browser cookies via a signed and encrypted seal. This provides client sessions that are ⚒️ iron-strong.
The seal stored on the client contains the session data, not your server, making it a "stateless" session from the server point of view. This is a different take than next-session where the cookie contains a session ID to then be used to map data on the server-side.
Online demo at https://next-iron-session.now.sh/ 👀
The seal is signed and encrypted using @hapi/iron, iron-store is used behind the scenes. This method of storing session data is the same technique used by frameworks like Ruby On Rails.
♻️ Password rotation is supported. It allows you to change the password used to sign and encrypt sessions while still being able to decrypt sessions that were created with a previous password.
Next.js's 🗿 Static generation (SG) and ⚙️ Server-side Rendering (SSR) are both supported.
There's a Connect middleware available so you can use this library in any Connect compatible framework like Express.
By default the cookie has an ⏰ expiration time of 15 days, set via maxAge
. After that, even if someone tries to reuse the cookie, next-iron-session
will not accept the underlying seal because the expiration is part of the seal value. See https://hapi.dev/family/iron for more information on @hapi/iron mechanisms.
Table of contents:
npm add next-iron-session
yarn add next-iron-session
You can find full featured examples (Next.js, Express) in the examples folder.
The password is a private key you must pass at runtime, it has to be at least 32 characters long. Use https://1password.com/password-generator/ to generate strong passwords.
⚠️ Always store passwords in secret environment variables on your platform.
// pages/api/login.js
import { withIronSession } from "next-iron-session";
async function handler(req, res) {
// get user from database then:
req.session.set("user", {
id: 230,
admin: true,
});
await req.session.save();
res.send("Logged in");
}
export default withIronSession(handler, {
password: "complex_password_at_least_32_characters_long",
cookieName: "myapp_cookiename",
// if your localhost is served on http:// then disable the secure flag
cookieOptions: {
secure: process.env.NODE_ENV === "production",
},
});
// pages/api/user.js
import { withIronSession } from "next-iron-session";
function handler(req, res, session) {
const user = req.session.get("user");
res.send({ user });
}
export default withIronSession(handler, {
password: "complex_password_at_least_32_characters_long",
cookieName: "myapp_cookiename",
// if your localhost is served on http:// then disable the secure flag
cookieOptions: {
secure: process.env.NODE_ENV === "production",
},
});
// pages/api/logout.js
import { withIronSession } from "next-iron-session";
function handler(req, res, session) {
req.session.destroy();
res.send("Logged out");
}
export default withIronSession(handler, {
password: "complex_password_at_least_32_characters_long",
cookieName: "myapp_cookiename",
// if your localhost is served on http:// then disable the secure flag
cookieOptions: {
secure: process.env.NODE_ENV === "production",
},
});
⚠️ Sessions are automatically recreated (empty session though) when:
Also see the full TypeScript example.
// pages/api/login.ts
import { NextApiRequest, NextApiResponse } from "next";
import { withIronSession, Session } from "next-iron-session";
type NextIronRequest = NextApiRequest & { session: Session };
async function handler(
req: NextIronRequest,
res: NextApiResponse,
): Promise<void> {
// get user from database then:
req.session.set("user", {
id: 230,
admin: true,
});
await req.session.save();
res.send("Logged in");
}
export default withIronSession(handler, {
password: "complex_password_at_least_32_characters_long",
cookieName: "myapp_cookiename",
// if your localhost is served on http:// then disable the secure flag
cookieOptions: {
secure: process.env.NODE_ENV === "production",
},
});
When you want to:
Then you can use multiple passwords:
Week 1:
export default withIronSession(handler, {
password: [
{
id: 1,
password: "complex_password_at_least_32_characters_long",
},
],
});
Week 2:
export default withIronSession(handler, {
password: [
{
id: 2,
password: "another_password_at_least_32_characters_long",
},
{
id: 1,
password: "complex_password_at_least_32_characters_long",
},
],
});
Notes:
id
is required so that we do not have to try every password in the list when decrypting (the id
is part of the cookie value).seal
) is always the first one in the array, so when rotating to put a new password, it must be first in the array liststring
) was given {id:1}
automatically.ironSession
You can import and use ironSession
if you want to use next-iron-session
in Express and Connect.
import { ironSession } from "next-iron-session";
const session = ironSession({
cookieName: "next-iron-session/examples/express",
password: process.env.SECRET_COOKIE_PASSWORD,
// if your localhost is served on http:// then disable the secure flag
cookieOptions: {
secure: process.env.NODE_ENV === "production",
},
});
router.get("/profile", session, async function (req, res) {
// now you can access all of the req.session.* utilities
if (req.session.get("user") === undefined) {
res.redirect("/restricted");
return;
}
res.render("profile", {
title: "Profile",
userId: req.session.get("user").id,
});
});
A more complete example using Express can be found in the examples folder.
next-connect
Since ironSession
is an Express / Connect middleware, it means you can use it with next-connect
:
import { ironSession } from "next-iron-session";
const session = ironSession({
cookieName: "next-iron-session/examples/express",
password: process.env.SECRET_COOKIE_PASSWORD,
// if your localhost is served on http:// then disable the secure flag
cookieOptions: {
secure: process.env.NODE_ENV === "production",
},
});
import nextConnect from "next-connect";
const handler = nextConnect();
handler.use(session).get((req, res) => {
const user = req.session.get("user");
res.send(`Hello user ${user.id}`);
});
export default handler;
This can be used to wrap Next.js getServerSideProps
or API Routes so you can then access all req.session.*
methods.
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 storedttl
, optional: In seconds, default to 14 dayscookieOptions
, optional: Any option available from jshttp/cookie#serialize. Default to:{
httpOnly: true,
secure: true,
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 server 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 next-iron-session already
// expires, there should be no need to use this option, maxAge takes precedence
}
Connect middleware.
import { ironSession } from "next-iron-session";
app.use(ironSession({ ...options }));
Allows you to use this module the way you want as long as you have access to req
and res
.
import { applySession } from "next-iron-session";
await applySession(req, res, options);
Note: If you use req.session.destroy()
in an API route, you need to make sure this route will not be cached. To do so, either call this route via a POST request fetch("/api/logout", { method: "POST" })
or add cache-control: no-store, max-age=0
to its response.
See https://github.com/vvo/next-iron-session/issues/274 for more details.
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.
There are some drawbacks to this approach:
next-iron-session
to accept basic auth or bearer token methods too. Open an issue if you're interested.next-iron-session
cookie containing {user: {id: 230, admin: true}}
is 358 bytes signed and encrypted: still plenty of available cookie space in here.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.
Not so much:
Depending on your own needs and preferences, next-iron-session
may or may not fit you.
This is a recent library I authored because I needed it. While @hapi/iron is battle-tested and used in production on a lot of websites, this library is not (yet!). Please use it at your own risk.
If you find bugs or have API ideas, create an issue.
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.
FAQs
Next.js stateless session utility using signed and encrypted cookies to store data
The npm package next-iron-session receives a total of 3,317 weekly downloads. As such, next-iron-session popularity was classified as popular.
We found that next-iron-session demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer 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
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.