Adding login functionality to a Next.js application involves several steps. Here's a basic guide:
Create a login page: First, you need to create a page where users can enter their credentials. This can be done using a form with email and password fields.
// pages/login.js
import { useState } from 'react';
export default function Login() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
// handle login here
};
return (
<form onSubmit={handleSubmit}>
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
<button type="submit">Login</button>
</form>
);
}
Handle login: You need to handle the login process when the form is submitted. This usually involves sending a request to your server with the user's credentials, and then handling the response.
import { useState } from 'react';
import axios from 'axios';
export default function Login() {
// ...
const handleSubmit = async (event) => {
event.preventDefault();
try {
const response = await axios.post('/api/login', { email, password });
// handle successful login
} catch (error) {
// handle login error
}
};
// ...
}
Authenticate users: On the server side, you need to authenticate the user's credentials. This usually involves checking the provided email and password against a database of users.
// pages/api/login.js
import { compareSync } from 'bcryptjs';
import { findUserByEmail } from '../../lib/users';
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).end();
}
const { email, password } = req.body;
const user = await findUserByEmail(email);
if (!user || !compareSync(password, user.password)) {
return res.status(401).json({ message: 'Invalid credentials' });
}
// successful login
res.status(200).json({ message: 'Logged in successfully' });
}
Store user session: After a successful login, you usually want to store some information about the user so that you can identify them in future requests. This can be done using cookies, JWT tokens, or other methods.
Protect routes: Finally, you need to protect certain routes so that only logged-in users can access them. This can be done using middleware that checks if the user is authenticated before allowing access to the route.
This is a very basic guide and the actual implementation can be much more complex depending on your requirements. For example, you might want to use a library like NextAuth.js to handle authentication, or you might want to use a service like Firebase or Auth0.
