Overview
To create a very simple login page using Next.js (frontend), Express.js (backend), and PostgreSQL (database), you need to:
- Set up a PostgreSQL database for user storage.
- Build an Express.js backend with endpoints for login (and optionally registration).
- Connect your backend to PostgreSQL.
- Create a Next.js frontend with a login form that communicates with the backend.
Below is a concise, step-by-step guide with code snippets for each part.
1. PostgreSQL: User Table Setup
Create a simple users table:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL
);
- Store passwords as hashed values (never plain text).
2. Express.js Backend
Install dependencies:
npm install express pg bcryptjs cors jsonwebtoken
Basic Express.js server (server.js):
const express = require('express');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const { Pool } = require('pg');
const jwt = require('jsonwebtoken');
const app = express();
app.use(cors());
app.use(express.json());
const pool = new Pool({
connectionString: process.env.DATABASE_URL, // Set this in your .env file
});
// Registration endpoint (optional)
app.post('/api/register', async (req, res) => {
const { email, password } = req.body;
const hashed = await bcrypt.hash(password, 10);
try {
await pool.query('INSERT INTO users (email, password) VALUES ($1, $2)', [email, hashed]);
res.status(201).json({ message: 'User registered' });
} catch (err) {
res.status(400).json({ error: 'User already exists' });
}
});
// Login endpoint
app.post('/api/login', async (req, res) => {
const { email, password } = req.body;
const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
const user = result.rows;
if (!user) return res.status(401).json({ error: 'Invalid credentials' });
const valid = await bcrypt.compare(password, user.password);
if (!valid) return res.status(401).json({ error: 'Invalid credentials' });
// Generate JWT token
const token = jwt.sign({ id: user.id, email: user.email }, 'your_jwt_secret');
res.json({ token });
});
app.listen(4000, () => console.log('Server running on port 4000'));
- Use environment variables for sensitive data.
- Use JWT for stateless authentication[6][9].
3. Next.js Frontend
Install dependencies:
npx create-next-app@latest my-login-app
cd my-login-app
npm install axios
Create a simple login page (pages/login.js):
import { useState } from 'react';
import axios from 'axios';
export default function Login() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
const handleLogin = async (e) => {
e.preventDefault();
try {
const res = await axios.post('http://localhost:4000/api/login', { email, password });
setMessage('Login successful! Token: ' + res.data.token);
// Store token in localStorage or cookie for authenticated requests
} catch (err) {
setMessage('Login failed: ' + err.response.data.error);
}
};
return (
<form onsubmit="{handleLogin}">
<input =="" onchange="{e" type="email" value="{email}"/> setEmail(e.target.value)} placeholder="Email" required />
<input =="" onchange="{e" type="password" value="{password}"/> setPassword(e.target.value)} placeholder="Password" required />
<button type="submit">Login</button>
<div>{message}</div>
</form>
);
}
- Adjust the backend URL as needed for deployment.
4. Connecting Everything
- Start PostgreSQL and ensure your
users table exists.
- Run the Express.js server (
node server.js).
- Run the Next.js app (
npm run dev in your Next.js directory).
- Register a user (via
/api/register or manually insert into DB), then log in using the Next.js form.
5. Security Notes
- Always hash passwords before storing them[5][6][9].
- Use HTTPS in production.
- Use environment variables for secrets and DB credentials.
References for Further Reading
- [Express.js + PostgreSQL + JWT authentication tutorial][6][7][9]
- [Connecting Next.js to PostgreSQL][8]
- [Full-stack PENN stack example][10]
This setup provides a minimal, secure login flow using Next.js, Express.js, and PostgreSQL. For production, consider using established authentication libraries and more robust error handling[1][4][5].