Skip to content

Conversation

@DikshantJangra
Copy link

Full-Stack JWT Authentication System

Overview

This PR implements a complete authentication system with JWT-based security, connecting a Node.js/Express backend with a React (Vite) frontend. The architecture emphasizes backend security, database management with Prisma ORM, and seamless API integration.


🏗️ Backend Architecture (Focus)

Tech Stack

  • Runtime: Node.js (ES Modules)
  • Framework: Express.js v5
  • Database: MySQL with Prisma ORM
  • Authentication: JWT (jsonwebtoken)
  • Security: bcrypt for password hashing
  • CORS: Enabled for cross-origin requests

Project Structure

backend/
├── src/
│ ├── controllers/
│ │ └── authController.js # Business logic for auth
│ ├── routes/
│ │ └── authRoutes.js # API route definitions
│ ├── utils/
│ │ ├── hashPassword.js # Password hashing utilities
│ │ └── token.js # JWT generation & verification
│ ├── db/
│ │ └── prisma.js # Prisma client instance
│ ├── index.js # Express app configuration
│ └── server.js # Server initialization
├── prisma/
│ └── schema.prisma # Database schema
└── .env # Environment variables


🔑 Core Backend Components

1. Database Schema (Prisma)

model User {
  id       Int    @id @default(autoincrement())
  name     String
  email    String @unique
  password String
}

Copy

Insert at cursor
MySQL database with Prisma ORM

User model with unique email constraint

Auto-incrementing primary key

2. Password Security
File: utils/hashPassword.js

Uses bcrypt with salt rounds = 10

hashPass(): Hashes plain passwords before storage

verifyPass(): Compares plain password with hashed version during login

3. JWT Token Management
File: utils/token.js

generateToken(): Creates JWT with userId payload

Token expiry: 7 days

Secret stored in environment variable (JWT_SECRET)

verifyTokens(): Validates JWT (currently unused but available)

4. Authentication Controller
File: controllers/authController.js

Signup Flow (POST /api/signup)
Validates required fields (name, email, password)

Checks if user already exists

Hashes password with bcrypt

Creates user in database via Prisma

Generates JWT token

Returns token to client

Login Flow (POST /api/login)
Validates email and password

Finds user by email

Verifies password using bcrypt

Generates JWT token

Returns token to client

5. API Routes
File: routes/authRoutes.js

POST /api/signup → signupUser

POST /api/login → loginUser

File: index.js

GET /api/users → Fetch all users (protected route)

GET / → Health check endpoint

6. Middleware Configuration
app.use(cors());           // Enable cross-origin requests
app.use(express.json());   // Parse JSON request bodies

Copy

Insert at cursor
🌐 Frontend Integration
Tech Stack
Framework: React 18 with Vite

HTTP Client: Axios

State Management: React Hooks (useState, useEffect)

Storage: localStorage for JWT persistence

API Communication
Signup Request
POST http://localhost:3001/api/signup
Body: { name, email, password }
Response: { message, token }

Copy

Insert at cursor
javascript
Login Request
POST http://localhost:3001/api/login
Body: { email, password }
Response: { message, token }

Copy

Insert at cursor
javascript
Fetch Users (Protected)
GET http://localhost:3001/api/users
Response: [{ id, name, email }]

Copy

Insert at cursor
javascript
Authentication Flow
User submits signup/login form

Frontend sends credentials to backend API

Backend validates, hashes password, generates JWT

Frontend stores JWT in localStorage

Token persists across page refreshes

Protected routes use token for authorization

Logout clears token from storage

🔄 Request-Response Cycle
┌─────────────┐                    ┌─────────────┐
│   React     │                    │   Express   │
│  Frontend   │                    │   Backend   │
└──────┬──────┘                    └──────┬──────┘
       │                                  │
       │  POST /api/signup                │
       │  { name, email, password }       │
       ├─────────────────────────────────>│
       │                                  │
       │                           Check existing user
       │                           Hash password (bcrypt)
       │                           Save to MySQL (Prisma)
       │                           Generate JWT
       │                                  │
       │  { message, token }              │
       │<─────────────────────────────────┤
       │                                  │
   Store token                            │
   in localStorage                        │
       │                                  │
       │  GET /api/users                  │
       ├─────────────────────────────────>│
       │                                  │
       │                           Fetch from database
       │                                  │
       │  [{ id, name, email }]           │
       │<─────────────────────────────────┤
       │                                  │


Copy

Insert at cursor
🚀 Running the Application
Backend
cd backend
npm install
npm run dev  # Runs on http://localhost:3001

Copy

Insert at cursor
bash
Frontend
cd frontend/vite
npm install
npm run dev  # Runs on http://localhost:5173

Copy

Insert at cursor
bash
🔒 Security Features
✅ Password Hashing: bcrypt with salt rounds
✅ JWT Authentication: Secure token-based auth
✅ Email Uniqueness: Database constraint prevents duplicates
✅ Input Validation: Required field checks
✅ Error Handling: Proper HTTP status codes
✅ CORS Configuration: Controlled cross-origin access

📝 Environment Variables
DATABASE_URL="mysql://user:password@localhost:3306/dbname"
JWT_SECRET="your-secret-key"
PORT=3001

Copy

Insert at cursor
env
🎯 Key Takeaways
Modular Backend: Separation of concerns (routes, controllers, utils)

Prisma ORM: Type-safe database queries

Stateless Auth: JWT eliminates server-side session storage

RESTful API: Clean endpoint design

Frontend Simplicity: No router needed, conditional rendering only

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant