1. Initialize a Node.js project and install dependencies:
bashnpm init -ynpm install prisma @prisma/client bcrypt jsonwebtoken dotenv expressnpm install -D typescript ts-node @types/express @types/node @types/bcrypt @types/jsonwebtoken
1. Create a .env file for environment variables:
bashDATABASE_URL="postgresql://USER:PASSWORD@localhost:5432/DB_NAME?schema=public"JWT_SECRET="your_jwt_secret_key"
you can generate a secure JWT secret using one of the following methods:
bashnode -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
b. Using Online Tools
You can use online tools like: - RandomKeygen - UUID Generator
c. Using OpenSSL
bashopenssl rand -hex 32
1. Initialize Prisma and create the User model in prisma/schema.prisma:
bash// prisma/schema.prismagenerator client {provider = "prisma-client-js"}datasource db {provider = "postgresql"url = env("DATABASE_URL")}model User {id Int @id @default(autoincrement())email String @uniquepassword Stringname String?}
2. Run migrations to create the database tables:
bashnpx prisma migrate dev --name init
Password Hashing (using bcrypt):
JWT Token Generation (using jsonwebtoken):
javascriptimport bcrypt from "bcrypt";import jwt from "jsonwebtoken";const saltRounds = 10;// Hash passwordexport const hashPassword = async (password) => {return await bcrypt.hash(password, saltRounds);};// Compare passwordexport const comparePassword = async (password, hash) => {return await bcrypt.compare(password, hash);};// Generate JWT tokenexport const generateToken = (userId) => {return jwt.sign({ userId }, process.env.JWT_SECRET, { expiresIn: "1h" });};// // Verify a tokenexport const validateToken = (req, res, next) => {const token = req.headers.authorization?.split(" ")[1];if (!token) return res.status(401).json({ error: "Unauthorized" });try {const decoded = jwt.verify(token, process.env.JWT_SECRET);req.user = decoded;next();} catch (error) {res.status(401).json({ error: "Invalid token" });}};
javascriptimport express from 'express';import { PrismaClient } from '@prisma/client';import { hashPassword, comparePassword, generateToken } from './utils/auth';const prisma = new PrismaClient();const app = express();app.use(express.json());// Register a new userapp.post('/register', async (req, res) => {const { email, password, name } = req.body;try {const hashedPassword = await hashPassword(password);const user = await prisma.user.create({data: {email,password: hashedPassword,name,},});res.status(201).json({ id: user.id, email: user.email });} catch (error) {res.status(400).json({ error: 'User already exists' });}});// Loginapp.post('/login', async (req, res) => {const { email, password } = req.body;const user = await prisma.user.findUnique({ where: { email } });if (!user) return res.status(404).json({ error: 'User not found' });const isValid = await comparePassword(password, user.password);if (!isValid) return res.status(401).json({ error: 'Invalid password' });const token = generateToken(user.id);res.json({ token });});const PORT = 3000;app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
node index.js
for MVC routing architecture look at my github repository where you can clone and run with configured routes and best practices
then cd postgres30-01
