Written by Sümeyye Sever (notes I took while creating web development projects)
→ npm install iron-session
iron-sessionis a lightweight session management library in Node.js for encrypting and signing session data on the client side.
// this code sets up session management for a web application using iron-session.
import { SessionOptions } from "iron-session"
export interface SessionData {
userId?:string,
username?:string,
user_email?:string,
isLoggedIn?: boolean,
}; // defines the *structure* of the session data
export const defaultSession: SessionData = {
isLoggedIn: false
} // specifies default session values
export const sessionOptions: SessionOptions = {
password: process.env.SECRET_KEY,
cookieName: "tickit-session",
cookieOptions: {
httpOnly: true,
secure: process.env.NODE_ENV === "production"
}
}; // configures session behavior and cookie settings,
// ensuring encrypted and secure session storage.
// you create the password and cookieName
// password should be at least 32 characters
// -> openssl rand -base64 32 (this will create a 32 chars random password)
"use server"
import { getIronSession } from "iron-session"
import { defaultSession, SessionData, sessionOptions } from "./utilsiron"
import { cookies } from "next/headers"
import { getUser } from "../lib/data"
import { redirect } from "next/navigation"
export const getSession = async () => {
const session = await getIronSession<SessionData>(cookies(), sessionOptions);
// fetches or initializes the session using cookies and the sessionOptions configuration.
if (!session.isLoggedIn) {
session.isLoggedIn = defaultSession.isLoggedIn;
} // if the isLoggedIn property isn't set in the session, it defaults to the value from defaultSession.
return session;
}
// login functions' purpose: logs in a user by validating credentials and saving session data.
export const login = async (
prevState: { error: undefined | string },
formData: FormData
) => {
const session = await getSession();
const formUseremail = formData.get("user_email") as string;
const formPassword = formData.get("password") as string;
const user = await getUser(formUseremail, formPassword);
// validates the credentials. if the user is found, their data is returned.
if (user) {
session.userId = user._id;
session.username = user.username;
session.user_email = formUseremail;
session.isLoggedIn = true;
await session.save();
redirect("/");
}
else {
return { error: "Wrong Credentials!" }
}
// updates the session with the user's ID, username, and email.
// await session.save(): saves the session changes to the *cookie*.
};
// logout functions' purpose: logs out a user by destroying their session.
export const logout = async () => {
const session = await getSession();
session.destroy();
redirect("/");
} // retrieves the current session and delete the session data.