How to Use Session in Next.js: Simple Guide with Example
In Next.js, you can manage sessions by using libraries like
next-auth for authentication or iron-session for custom session handling. These libraries let you store and access session data securely on the server and client side with simple API routes or hooks.Syntax
Using iron-session, you create a session configuration and wrap your API routes or pages to read/write session data. The main parts are:
withIronSessionApiRoute: wraps API routes to handle sessions.withIronSessionSsr: wraps server-side rendering functions to access sessions.sessionOptions: configuration object with cookie name, password, and security settings.
typescript
import { withIronSessionApiRoute } from "iron-session/next"; const sessionOptions = { password: process.env.SECRET_COOKIE_PASSWORD, cookieName: "myapp_session", cookieOptions: { secure: process.env.NODE_ENV === "production", }, }; async function handler(req, res) { // Set session data req.session.user = { id: 1, name: "Alice" }; await req.session.save(); res.send({ ok: true }); } export default withIronSessionApiRoute(handler, sessionOptions);
Example
This example shows a simple Next.js API route that sets and reads a user session using iron-session. It stores a user object in the session and returns it on request.
typescript
import { withIronSessionApiRoute } from "iron-session/next"; const sessionOptions = { password: "complex_password_at_least_32_characters_long", cookieName: "nextjs_session", cookieOptions: { secure: process.env.NODE_ENV === "production", }, }; async function handler(req, res) { if (req.method === "POST") { const { user } = req.body; req.session.user = user; await req.session.save(); res.status(200).json({ message: "Session saved" }); } else if (req.method === "GET") { const user = req.session.user; res.status(200).json({ user: user || null }); } else { res.status(405).end(); } } export default withIronSessionApiRoute(handler, sessionOptions);
Output
{"user":{"id":1,"name":"Alice"}}
Common Pitfalls
- Not setting a strong
passwordforiron-sessioncan cause security issues. - Forgetting to call
await req.session.save()after modifying session data means changes won't persist. - Using
secure: truein cookie options during development without HTTPS will prevent cookies from being set. - Trying to access session data on the client side directly without API routes or hooks will not work.
typescript
/* Wrong: Missing await on session.save() */ async function handler(req, res) { req.session.user = { id: 1 }; req.session.save(); // Missing await, session might not save res.end(); } /* Right: Await session.save() */ async function handler(req, res) { req.session.user = { id: 1 }; await req.session.save(); res.end(); }
Quick Reference
Remember these key points when using sessions in Next.js:
- Use
iron-sessionornext-authfor session management. - Configure session options carefully, especially
passwordandcookieOptions. - Always
awaitsaving session changes. - Access sessions only in API routes or server-side functions.
Key Takeaways
Use libraries like iron-session or next-auth to handle sessions securely in Next.js.
Always await session.save() after modifying session data to persist changes.
Configure cookie options properly to avoid issues in development and production.
Access session data only in API routes or server-side functions, not directly on the client.
Use strong passwords for session encryption to keep user data safe.