How to create an Authentication & Authorization feature in Next JS 14 with another backend?
Published: 2024-06-04 05:42:51

To create an authentication and authorization feature in Next.js 14 with another backend, you typically need to use a third-party authentication provider or a custom backend API. Here, I'll demonstrate how to do this using Next.js with NextAuth.js as the authentication library and a custom backend (e.g., an Express.js server) for handling authentication logic.

### Step 1: Set Up the Next.js Project

1. **Initialize a New Project:**
   ```bash
   npx create-next-app@latest my-nextjs-app
   cd my-nextjs-app
   ```

2. **Install Required Packages:**
   ```bash
   npm install next-auth axios
   ```

### Step 2: Configure NextAuth.js

1. **Create the Auth API Route:**
   Create `src/pages/api/auth/[...nextauth].js`:
   ```javascript
   import NextAuth from 'next-auth';
   import Providers from 'next-auth/providers';
   import axios from 'axios';

   export default NextAuth({
     providers: [
       Providers.Credentials({
         async authorize(credentials) {
           try {
             const res = await axios.post('http://localhost:4000/api/auth/login', {
               email: credentials.email,
               password: credentials.password,
             });

             if (res.data && res.data.token) {
               return { token: res.data.token, user: res.data.user };
             }
             return null;
           } catch (error) {
             throw new Error('Invalid email or password');
           }
         },
       }),
     ],
     callbacks: {
       async jwt(token, user) {
         if (user) {
           token.accessToken = user.token;
           token.user = user.user;
         }
         return token;
       },
       async session(session, token) {
         session.accessToken = token.accessToken;
         session.user = token.user;
         return session;
       },
     },
     pages: {
       signIn: '/login',
     },
   });
   ```

### Step 3: Create the Custom Backend (Express.js)

1. **Set Up an Express.js Server:**
   ```bash
   mkdir my-express-backend
   cd my-express-backend
   npm init -y
   npm install express mongoose bcryptjs jsonwebtoken cors
   ```

2. **Configure Environment Variables:**
   Create a `.env` file in the root of your backend project:
   ```plaintext
   PORT=4000
   MONGODB_URI=mongodb://localhost:27017/auth-db
   JWT_SECRET=your_jwt_secret
   ```

3. **Create User Model:**
   Create `src/models/User.js`:
   ```javascript
   const mongoose = require('mongoose');
   const bcrypt = require('bcryptjs');

   const UserSchema = new mongoose.Schema({
     name: { type: String, required: true },
     email: { type: String, required: true, unique: true },
     password: { type: String, required: true },
   });

   UserSchema.pre('save', async function(next) {
     if (!this.isModified('password')) return next();
     const salt = await bcrypt.genSalt(10);
     this.password = await bcrypt.hash(this.password, salt);
     next();
   });

   UserSchema.methods.matchPassword = async function(enteredPassword) {
     return await bcrypt.compare(enteredPassword, this.password);
   };

   module.exports = mongoose.model('User', UserSchema);
   ```

4. **Create Authentication Controller:**
   Create `src/controllers/authController.js`:
   ```javascript
   const jwt = require('jsonwebtoken');
   const User = require('../models/User');
   const bcrypt = require('bcryptjs');

   exports.registerUser = async (req, res) => {
     const { name, email, password } = req.body;

     const userExists = await User.findOne({ email });
     if (userExists) return res.status(400).json({ message: 'User already exists' });

     const user = await User.create({ name, email, password });

     if (user) {
       res.status(201).json({ message: 'User registered successfully' });
     } else {
       res.status(400).json({ message: 'Invalid user data' });
     }
   };

   exports.loginUser = async (req, res) => {
     const { email, password } = req.body;

     const user = await User.findOne({ email });
     if (!user || !(await user.matchPassword(password))) {
       return res.status(401).json({ message: 'Invalid email or password' });
     }

     const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
     res.json({ token, user: { id: user._id, name: user.name, email: user.email } });
   };
   ```

5. **Create Routes:**
   Create `src/routes/authRoutes.js`:
   ```javascript
   const express = require('express');
   const { registerUser, loginUser } = require('../controllers/authController');

   const router = express.Router();

   router.post('/register', registerUser);
   router.post('/login', loginUser);

   module.exports = router;
   ```

6. **Set Up Express.js Server:**
   Create `src/index.js`:
   ```javascript
   const express = require('express');
   const mongoose = require('mongoose');
   const cors = require('cors');
   const authRoutes = require('./routes/authRoutes');
   require('dotenv').config();

   const app = express();

   app.use(cors());
   app.use(express.json());

   mongoose.connect(process.env.MONGODB_URI, {
     useNewUrlParser: true,
     useUnifiedTopology: true,
   });

   app.use('/api/auth', authRoutes);

   const PORT = process.env.PORT || 4000;
   app.listen(PORT, () => {
     console.log(`Server running on port ${PORT}`);
   });
   ```

### Step 4: Set Up Client-Side Authentication in Next.js

1. **Create Login Page:**
   Create `src/pages/login.js`:
   ```javascript
   import { useState } from 'react';
   import { signIn } from 'next-auth/react';
   import { useRouter } from 'next/router';

   const Login = () => {
     const [email, setEmail] = useState('');
     const [password, setPassword] = useState('');
     const [error, setError] = useState('');
     const router = useRouter();

     const handleSubmit = async (e) => {
       e.preventDefault();

       const result = await signIn('credentials', {
         redirect: false,
         email,
         password,
       });

       if (result.ok) {
         router.push('/');
       } else {
         setError(result.error);
       }
     };

     return (
       <form onSubmit={handleSubmit}>
         <div>
           <label>Email</label>
           <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
         </div>
         <div>
           <label>Password</label>
           <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
         </div>
         {error && <p>{error}</p>}
         <button type="submit">Login</button>
       </form>
     );
   };

   export default Login;
   ```

2. **Protect Pages (Client-Side):**
   Create a higher-order component (HOC) to protect pages:
   ```javascript
   import { useSession } from 'next-auth/react';
   import { useRouter } from 'next/router';
   import { useEffect } from 'react';

   const withAuth = (WrappedComponent) => {
     return (props) => {
       const { data: session, status } = useSession();
       const router = useRouter();

       useEffect(() => {
         if (status === 'unauthenticated') {
           router.replace('/login');
         }
       }, [status, router]);

       if (status === 'authenticated') {
         return <WrappedComponent {...props} />;
       }

       return null;
     };
   };

   export default withAuth;
   ```

   Usage:
   ```javascript
   import withAuth from '../path/to/withAuth';

   const ProtectedPage = () => {
     return (
       <div>
         <h1>Protected Content</h1>
       </div>
     );
   };

   export default withAuth(ProtectedPage);
   ```

### Step 5: Start the Applications

1. **Run the Next.js Application:**
   ```bash
   npm run dev
   ```

2. **Run the Express.js Backend:**
   ```bash
   node src/index.js
   ```

### Step 6: Test the Application

1. **Register a User:**
   - Use a tool like Postman to send a POST request to `http://localhost:4000/api/auth/register` with the user's details.

2. **Login a User:**
   - Navigate to `/login` in your Next.js application and log in with the registered user.

3. **Access Protected Page:**
   - Navigate to a protected page, e.g., `/profile`, to ensure it redirects to `/login` when not authenticated and displays the content when authenticated.

This guide provides a foundational approach to implementing authentication and authorization in a Next.js 14 application with a separate backend. You can further expand and customize it based on your application's requirements.

Disclaimer: This content is generated by AI.