DEV Community

Abdur Rakib Rony
Abdur Rakib Rony

Posted on

Implementing Secure Authentication in Next.js with JWT and MongoDB. Protect Routes using middleware

In modern web development, implementing a robust authentication system is crucial for securing user data and providing a seamless user experience. In this blog post, we'll explore how to implement authentication in a Next.js application using JSON Web Tokens (JWT) and MongoDB. We'll cover the key aspects of this implementation, including middleware, token management, and user registration and login.

Setting Up Middleware for Route Protection
The middleware function plays a crucial role in protecting routes and ensuring that users are authenticated before accessing certain pages. Here's the implementation of the middleware function:

import { getToken, verifyToken } from "@/lib/auth";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export async function middleware(request: NextRequest) {
  const token = getToken(request);
  const { pathname } = request.nextUrl;

  if (token) {
    const payload = await verifyToken(token);
    if (payload) {
      if (pathname === "/" || pathname === "/register") {
        return NextResponse.redirect(new URL("/home", request.url));
      }
      return NextResponse.next();
    }
  }

  if (pathname !== "/" && pathname !== "/register") {
    return NextResponse.redirect(new URL("/", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};

Enter fullscreen mode Exit fullscreen mode

This middleware function checks if a token exists and verifies it. If the token is valid, it allows the user to proceed to the requested route. If the token is invalid or missing, it redirects the user to the login page.

Managing Tokens with JSON Web Tokens (JWT)
To handle token generation and verification, we use the jose library. Below are the utility functions for managing JWTs:

import { jwtVerify, SignJWT } from 'jose';
import { NextRequest } from "next/server";

export function getToken(req: NextRequest) {
  return req.cookies.get("token")?.value;
}

export async function verifyToken(token: string) {
  if (!token) return null;

  try {
    const secret = new TextEncoder().encode(process.env.JWT_SECRET);
    const { payload } = await jwtVerify(token, secret);
    return payload as { userId: string };
  } catch (error) {
    console.error('Token verification failed:', error);
    return null;
  }
}

export async function createToken(payload: { userId: string }) {
  const secret = new TextEncoder().encode(process.env.JWT_SECRET!);
  const token = await new SignJWT(payload)
    .setProtectedHeader({ alg: 'HS256' })
    .setExpirationTime('1d')
    .sign(secret);
  return token;
}

Enter fullscreen mode Exit fullscreen mode

These functions handle retrieving the token from cookies, verifying the token, and creating a new token. The verifyToken function ensures that the token is valid and extracts the payload, while createToken generates a new token with a specified payload.

User Registration and Login
For user registration and login, we need to handle form data, hash passwords, and create tokens. Here's how we achieve this:

"use server";
import { cookies } from "next/headers";
import bcrypt from "bcryptjs";
import { connectToDB } from "@/lib/db";
import User from "@/models/User";
import { loginSchema, registerSchema } from "@/zod/schema";
import { createToken } from "@/lib/auth";

export async function registerUser(formData: FormData) {
  await connectToDB();

  const parsedData = registerSchema.parse(
    Object.fromEntries(formData.entries())
  );

  const existingUser = await User.findOne({ email: parsedData.email });
  if (existingUser) {
    throw new Error("Email already exists");
  }

  const hashedPassword = await bcrypt.hash(parsedData.password, 10);

  const newUser = await User.create({
    ...parsedData,
    password: hashedPassword,
    createdAt: new Date(),
  });

  const token = await createToken({ userId: newUser._id.toString() });

  const cookieStore = cookies();
  cookieStore.set("token", token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
  });
}

export async function loginUser(formData: FormData) {
  const { email, password } = loginSchema.parse(
    Object.fromEntries(formData.entries())
  );

  await connectToDB();

  const user = await User.findOne({ email });
  if (!user) {
    throw new Error("Invalid credentials");
  }

  const isPasswordValid = await bcrypt.compare(password, user.password);
  if (!isPasswordValid) {
    throw new Error("Invalid credentials");
  }

  const token = await createToken({ userId: user._id.toString() });

  const cookieStore = cookies();
  cookieStore.set("token", token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
  });
}

export async function logoutUser() {
  cookies().set("token", "", { expires: new Date(0) });
}

Enter fullscreen mode Exit fullscreen mode

registerUser: This function handles user registration. It connects to the database, parses the form data, checks if the email already exists, hashes the password, creates a new user, generates a token, and sets the token as an HTTP-only cookie.

loginUser: This function handles user login. It parses the form data, connects to the database, verifies the user's credentials, generates a token, and sets the token as an HTTP-only cookie.

logoutUser: This function handles user logout by clearing the token cookie.

Conclusion
Implementing authentication in a Next.js application using JWT and MongoDB provides a secure and efficient way to manage user sessions. By leveraging middleware, JWT, and MongoDB, we can protect routes, verify tokens, and handle user registration and login seamlessly.

Top comments (0)