How to Create a Login API in Express: Simple Guide
To create a login API in
Express, set up a POST route that accepts user credentials, verifies them against stored data, and responds with success or error messages. Use express.json() middleware to parse JSON requests and handle authentication logic inside the route handler.Syntax
The basic syntax to create a login API in Express involves defining a POST route with app.post(). Use req.body to access user input, then verify credentials and send a response with res.json() or res.status().
app.post('/login', handler): Defines the login endpoint.req.body: Contains the JSON data sent by the client.res.json(): Sends a JSON response.
javascript
app.post('/login', (req, res) => { const { username, password } = req.body; // authentication logic here if (username === 'user' && password === 'pass') { res.json({ message: 'Login successful' }); } else { res.status(401).json({ message: 'Invalid credentials' }); } });
Example
This example shows a complete Express app with a login API that checks hardcoded credentials and returns success or error messages.
javascript
import express from 'express'; const app = express(); app.use(express.json()); app.post('/login', (req, res) => { const { username, password } = req.body; // Simple hardcoded user check if (username === 'admin' && password === '1234') { res.json({ message: 'Login successful' }); } else { res.status(401).json({ message: 'Invalid username or password' }); } }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
Output
Server running on port 3000
Common Pitfalls
Common mistakes include not using express.json() middleware, which causes req.body to be undefined, and not handling incorrect credentials properly. Also, avoid sending sensitive info in responses.
Always respond with appropriate HTTP status codes like 401 Unauthorized for failed logins.
javascript
/* Wrong: Missing express.json middleware */ import express from 'express'; const app = express(); app.post('/login', (req, res) => { // req.body will be undefined const { username, password } = req.body || {}; if (username === 'admin' && password === '1234') { res.json({ message: 'Login successful' }); } else { res.status(401).json({ message: 'Invalid credentials' }); } }); /* Right: Include express.json middleware */ app.use(express.json());
Quick Reference
- Use
app.use(express.json())to parse JSON request bodies. - Define login route with
app.post('/login', handler). - Extract credentials from
req.body. - Validate credentials securely (e.g., hashed passwords in real apps).
- Send JSON response with success or error message.
- Use proper HTTP status codes (200 for success, 401 for unauthorized).
Key Takeaways
Always use express.json() middleware to parse JSON request bodies.
Create a POST route to handle login requests and extract credentials from req.body.
Validate user credentials and respond with appropriate HTTP status codes.
Avoid exposing sensitive information in API responses.
Test your API with tools like Postman or curl to verify behavior.