// pages/api/register.ts import type { NextApiRequest, NextApiResponse } from "next"; import { PrismaClient } from "@prisma/client"; import bcrypt from "bcrypt"; import jwt from "jsonwebtoken"; const prisma = new PrismaClient(); const SECRET_KEY = process.env.JWT_SECRET as string; export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" }); try { const { email, password } = req.body as { email?: string; password?: string }; if (!email || !password) return res.status(400).json({ message: "Email and password are required" }); const existingUser = await prisma.user.findUnique({ where: { email } }); if (existingUser) return res.status(400).json({ message: "User already exists" }); const hashedPassword = await bcrypt.hash(password, 10); const user = await prisma.user.create({ data: { email, password: hashedPassword }, select: { id: true, email: true, createdAt: true }, // do NOT expose password }); const token = jwt.sign({ sub: user.id, email: user.email }, SECRET_KEY, { expiresIn: "1d" }); // Set a secure, httpOnly cookie const maxAge = 60 * 60 * 24; // 1 day res.setHeader( "Set-Cookie", `token=${token}; HttpOnly; Path=/; Max-Age=${maxAge}; SameSite=Strict; Secure` ); return res.status(201).json({ message: "User registered", user }); } catch (err) { console.error(err); return res.status(500).json({ message: "Something went wrong" }); } }