![Create React App Officially Deprecated Amid React 19 Compatibility Issues](https://cdn.sanity.io/images/cgdhsj6q/production/04fa08cf844d798abc0e1a6391c129363cc7e2ab-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Create React App Officially Deprecated Amid React 19 Compatibility Issues
Create React App is officially deprecated due to React 19 issues and lack of maintenance—developers should switch to Vite or other modern alternatives.
iron-session-data
Advanced tools
Node.js stateless session utility using signed and encrypted cookies to store data.
⭐️ 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:
npm add 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 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.
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",
},
};
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,
},
};
},
);
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
See examples/express for an example of how to use this with Express.
When you want to:
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:
seal
) is always the highest number found in the map (2 in the example).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.
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");
}
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.
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.
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 storedttl
, 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
}
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",
},
};
},
);
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",
},
};
},
);
Creates an express middleware that adds a session
object to the request.
import { ironSession } from "iron-session/express";
app.use(ironSession(ironOptions));
Saves the session and sets the cookie header to be sent once the response is sent.
await req.session.save();
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.
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:
iron-session
to accept basic auth or bearer token methods too. Open an issue if you're interested.iron-session
cookie containing {user: {id: 100}}
is 265 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, iron-session
may or may not fit you.
✅ Production ready and maintained.
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.
Thanks goes to these wonderful people (emoji key):
John Vandivier 💻 🤔 💡 | searchableguy ⚠️ 📖 💻 |
This project follows the all-contributors specification. Contributions of any kind welcome!
FAQs
Node.js stateless session utility using signed and encrypted cookies to store data.
We found that iron-session-data 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
Create React App is officially deprecated due to React 19 issues and lack of maintenance—developers should switch to Vite or other modern alternatives.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.