Session และ Cookie เป็นสิ่งที่ขาดไม่ได้ในระบบเว็บแอป Next.js ไม่ว่าจะเป็นการ จัดการผู้ใช้ (Authentication), จดจำค่าต่างๆ หรือ รักษาความปลอดภัยของแอป
📌 บทความนี้จะอธิบายว่า Session & Cookie คืออะไร และ ใช้งานใน Next.js ยังไง พร้อมตัวอย่างโค้ดแบบจับมือทำ! 🚀
🎯 Session และ Cookie คืออะไร?
🍪 Cookie
Cookie เป็นข้อมูลเล็กๆ ที่ browser เก็บไว้ในเครื่องของผู้ใช้ โดยส่งไปพร้อมกับทุกๆ request เพื่อให้เซิร์ฟเวอร์จำผู้ใช้ได้
🔹 ใช้สำหรับ จดจำสถานะของผู้ใช้ (เช่นล็อกอินอยู่หรือเปล่า?)
🔹 สามารถตั้งค่า หมดอายุ (Expire) ได้
🔹 มีการจำกัดขนาดข้อมูล (โดยทั่วไปไม่เกิน 4KB)
🔐 Session
Session คือการเก็บข้อมูลของผู้ใช้ ฝั่งเซิร์ฟเวอร์ และอ้างอิงด้วย Session ID ที่เก็บไว้ใน Cookie
🔹 ปลอดภัยกว่าการเก็บข้อมูลใน Cookie เพราะข้อมูลไม่ได้ถูกเก็บไว้ที่ฝั่งผู้ใช้
🔹 ต้องใช้ Session Storage เช่น Redis, Database หรือ Memory
🔹 มีอายุการใช้งานตามที่กำหนด (เช่น 30 นาที)
💡 โดยทั่วไป Session & Cookie ใช้งานร่วมกัน คือ เก็บ Session ID ไว้ใน Cookie เพื่อให้เซิร์ฟเวอร์ดึงข้อมูลผู้ใช้มาใช้ได้
🚀 วิธีใช้งาน Cookie ใน Next.js
📌 ติดตั้งไลบรารีจัดการ Cookie
npm install cookie
🔹 สร้าง API ที่ใช้ Cookie ใน Next.js
📌 โค้ด: pages/api/auth/set-cookie.js
import { serialize } from "cookie";
export default function handler(req, res) {
const token = "my_secure_token"; // จำลอง token
res.setHeader("Set-Cookie", serialize("auth_token", token, {
httpOnly: true, // ป้องกันการเข้าถึงจาก JavaScript
secure: process.env.NODE_ENV === "production", // ใช้ https ในโหมด production
maxAge: 60 * 60 * 24, // 1 วัน
sameSite: "strict",
path: "/",
}));
res.json({ message: "Cookie set!" });
}
✅ API นี้จะสร้าง auth_token แล้วฝังไว้ใน Cookie
✅ ตั้งค่า httpOnly เพื่อให้ปลอดภัยจาก XSS
✅ หมดอายุใน 1 วัน
🔹 อ่านค่า Cookie
📌 โค้ด: pages/api/auth/get-cookie.js
import { parse } from "cookie";
export default function handler(req, res) {
const cookies = parse(req.headers.cookie || "");
res.json({ token: cookies.auth_token || "No token found" });
}
✅ API นี้จะอ่านค่า auth_token จาก Cookie
🔹 ลบ Cookie (Logout)
📌 โค้ด: pages/api/auth/logout.js
import { serialize } from "cookie";
export default function handler(req, res) {
res.setHeader("Set-Cookie", serialize("auth_token", "", {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
expires: new Date(0), // ลบ Cookie
path: "/",
}));
res.json({ message: "Logged out!" });
}
✅ API นี้จะลบ Cookie โดยตั้งค่า expire เป็น 0
🚀 วิธีใช้งาน Session ใน Next.js
📌 ติดตั้งไลบรารี Session
npm install next-session
next-session เป็นไลบรารีที่ช่วยจัดการ Session ใน Next.js API Routes ได้ง่าย
🔹 ตั้งค่า Session Middleware
📌 โค้ด: lib/session.js
import { withIronSessionApiRoute } from "iron-session/next";
export function withSession(handler) {
return withIronSessionApiRoute(handler, {
cookieName: "session_cookie",
password: "complex_password_123", // ควรใช้ env variable
cookieOptions: {
secure: process.env.NODE_ENV === "production",
},
});
}
✅ ใช้ iron-session เก็บ Session อย่างปลอดภัย
✅ ตั้งค่า session_cookie เป็นที่เก็บ Session
🔹 สร้าง API ที่ใช้ Session
📌 โค้ด: pages/api/auth/login.js
import { withSession } from "../../lib/session";
export default withSession(async function handler(req, res) {
if (req.method !== "POST") return res.status(405).json({ error: "Method Not Allowed" });
req.session.user = { id: 1, username: "admin" };
await req.session.save();
res.json({ message: "Login successful", user: req.session.user });
});
✅ เมื่อล็อกอินสำเร็จ จะเก็บข้อมูลผู้ใช้ใน Session
🔹 ดึงข้อมูลจาก Session
📌 โค้ด: pages/api/auth/me.js
import { withSession } from "../../lib/session";
export default withSession(async function handler(req, res) {
if (!req.session.user) {
return res.status(401).json({ error: "Not authenticated" });
}
res.json({ user: req.session.user });
});
✅ API นี้จะเช็กว่า มี Session ไหม? ถ้ามีแสดงข้อมูลผู้ใช้
🔹 ลบ Session (Logout)
📌 โค้ด: pages/api/auth/logout.js
import { withSession } from "../../lib/session";
export default withSession(async function handler(req, res) {
req.session.destroy();
res.json({ message: "Logged out!" });
});
✅ API นี้จะ ลบ Session แล้วทำให้ผู้ใช้ต้องล็อกอินใหม่
🎨 สร้างหน้า UI สำหรับ Login
📌 โค้ด: pages/index.js
import { useState } from "react";
export default function Home() {
const [message, setMessage] = useState("");
const login = async () => {
const res = await fetch("/api/auth/login", { method: "POST" });
const data = await res.json();
setMessage(data.message);
};
const checkSession = async () => {
const res = await fetch("/api/auth/me");
const data = await res.json();
setMessage(data.user ? `Logged in as ${data.user.username}` : "Not authenticated");
};
return (
<div>
<h1>Session & Cookie in Next.js</h1>
<button onClick={login}>Login</button>
<button onClick={checkSession}>Check Session</button>
<p>{message}</p>
</div>
);
}
✅ UI นี้จะ Login แล้วเช็กว่า Session ยังอยู่ไหม?
🚀 ทดสอบระบบ
- รันเซิร์ฟเวอร์ npm run dev
- เปิด http://localhost:3000
- กด Login แล้วดูว่ามี Session หรือไม่
🎯 สรุป
✅ Cookie – ใช้เก็บข้อมูลเล็กๆ ฝั่ง client
✅ Session – ใช้เก็บข้อมูลฝั่งเซิร์ฟเวอร์
✅ Next.js API Routes รองรับทั้ง Cookie & Session
✅ ใช้ iron-session ทำให้การจัดการ Session ง่ายขึ้น
ไม่มีความคิดเห็น:
แสดงความคิดเห็น