Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 79

Next.js Authentication UI for EKS

This lesson is built with resources from youtube.com, nextjs.org and 1 more site.

Hello! Welcome to the grand finale of our course.

In our last lesson, we put the final piece of our backend testing strategy in place by writing a full @SpringBootTest integration test using Testcontainers. This gave us the highest possible confidence that our Spring Boot application works correctly with a real PostgreSQL database. With our backend thoroughly tested and deployed to EKS, it's now time to build the client that will interact with it.

Today, we'll bridge the gap between the frontend and backend. Our goal is to build a minimal Next.js UI to perform user registration and login against the deployed EKS cluster.

As an experienced Next.js developer, you'll find the UI part straightforward. Our focus will be on implementing a modern, secure, and production-grade authentication flow using the Next.js App Router, connecting it to our live Spring Boot API. This lesson will tie together every concept we've covered, from backend API endpoints to cloud deployment.

1. The Modern Next.js Authentication Strategy

In many traditional single-page applications (SPAs), it was common to store JWTs in localStorage. However, this practice exposes your application to Cross-Site Scripting (XSS) attacks, where malicious scripts can steal tokens from storage.

The modern, secure approach, which we will implement, relies on HTTP-only cookies.

Next.js Secure Authentication using cookies and server actions

To understand the 'why' behind our chosen strategy, this article provides a concise explanation of the security risks of localStorage and introduces HTTP-only cookies as the superior alternative for web authentication.

Read the introductory section of the article, which covers the security vulnerabilities of using localStorage and explains why HTTP-only cookies are a more secure mechanism.

Here's how the flow works with our Spring Boot backend:

  1. The Next.js client sends login credentials to the backend via a Server Action.
  2. Our Spring Boot backend validates the credentials, generates JWTs (access and refresh tokens), and sends them back in Set-Cookie headers with the HttpOnly flag.
  3. The browser automatically stores these cookies. Because they are HttpOnly, client-side JavaScript (including malicious scripts) cannot access them.
  4. On subsequent requests to our backend's domain, the browser automatically attaches these cookies, authenticating the user.
  5. Next.js Server Components, Server Actions, and Middleware can read these cookies because they execute on the server, allowing us to manage the user's session securely.

This server-centric approach is a key pattern for building secure applications with the Next.js App Router.


2. Setting Up the Next.js Project

Let's get our project initialized.

  1. Create a new Next.js application:

    npx create-next-app@latest blog-platform-ui
    

    Choose the default options (TypeScript, Tailwind CSS, App Router).

  2. Folder Structure: We'll adopt a clean structure for our authentication routes. Grouping routes with parentheses (auth) is a standard pattern for creating route groups that don't affect the URL path.

Next.js 15 Optimized Folder Structure for Authentication
This image shows a recommended Next.js folder structure. We will follow a similar pattern, placing our `login` and `register` pages inside an `app/(auth)/` directory.

Create the following folder structure inside your app directory:

app/
├── (auth)/
│   ├── login/
│   │   └── page.tsx
│   └── register/
│       └── page.tsx
├── dashboard/
│   └── page.tsx
├── lib/
│   ├── actions.ts   // For Server Actions
│   └── session.ts   // For session management logic
└── layout.tsx
└── page.tsx
  1. Environment Variable: We need to tell our Next.js app where to find our backend. First, get the external URL of your API gateway from EKS:

    kubectl get ingress
    

    Look for the ADDRESS of your gateway ingress. It will be a URL like k8s-default-yourapi-....elb.amazonaws.com.

    Create a .env.local file in the root of your Next.js project and add this URL:

    API_BASE_URL=http://<YOUR_EKS_INGRESS_URL>
    

3. Implementing the Authentication UI and Logic

We'll now build the core components and server-side logic for registration and login. The video below demonstrates a very similar "roll-your-own" authentication flow and is an excellent visual guide for the concepts we're implementing.

Next.js App Router Authentication (Sessions, Cookies, JWTs)

This video from Lee Robinson, VP of Product at Vercel, walks through creating a session-based authentication flow from scratch using Server Actions and encrypted cookies. The principles are directly applicable to our task of interacting with our backend.

Watch the following parts: Introduction (00:00 - 01:18): Understand the basic setup using a Server Component and forms that call Server Actions. Login Logic (01:18 - 02:40): Pay attention to how the login server action receives form data, creates a session, and sets a cookie. Our logic will be slightly different (we call our backend API), but the pattern is the same. Session & Logout (06:08 - 07:07): See how session data is read from cookies on the server and how the logout action works by deleting the cookie.

Step 1: Registration Page and Server Action

First, let's build the registration form.

app/(auth)/register/page.tsx:

// app/(auth)/register/page.tsx
import { registerUser } from "@/app/lib/actions";

export default function RegisterPage() {
  return (
    <main className="flex items-center justify-center h-screen">
      <div className="w-full max-w-md p-8 space-y-6 bg-white rounded-lg shadow-md">
        <h1 className="text-2xl font-bold text-center">Register</h1>
        <form action={registerUser} className="space-y-4">
          <div>
            <label htmlFor="username">Username</label>
            <input id="username" name="username" type="text" required className="w-full p-2 border rounded" />
          </div>
          <div>
            <label htmlFor="email">Email</label>
            <input id="email" name="email" type="email" required className="w-full p-2 border rounded" />
          </div>
          <div>
            <label htmlFor="password">Password</label>
            <input id="password" name="password" type="password" required className="w-full p-2 border rounded" />
          </div>
          <button type="submit" className="w-full p-2 text-white bg-blue-600 rounded hover:bg-blue-700">
            Register
          </button>
        </form>
      </div>
    </main>
  );
}

Now, implement the registerUser Server Action that this form calls.

app/lib/actions.ts:

// app/lib/actions.ts
'use server';

import { redirect } from 'next/navigation';

const API_URL = process.env.API_BASE_URL;

export async function registerUser(formData: FormData) {
  const name = formData.get('username');
  const email = formData.get('email');
  const password = formData.get('password');

  try {
    const response = await fetch(`${API_URL}/api/auth/register`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name, email, password }),
    });

    if (!response.ok) {
      const errorData = await response.json();
      // In a real app, you'd handle this more gracefully
      throw new Error(errorData.message || 'Registration failed');
    }

    // On successful registration, redirect to login
    redirect('/login');

  } catch (error) {
    console.error(error);
    // Handle errors, maybe by returning a message to the UI
    // For now, we'll just log it.
  }
}

Step 2: Login Page and Server Action

The login page is very similar. The key difference is that on a successful login, our Spring Boot backend will send back Set-Cookie headers, which the browser will automatically handle.

app/(auth)/login/page.tsx:

// app/(auth)/login/page.tsx
import { loginUser } from "@/app/lib/actions";

export default function LoginPage() {
  return (
    <main className="flex items-center justify-center h-screen">
      <div className="w-full max-w-md p-8 space-y-6 bg-white rounded-lg shadow-md">
        <h1 className="text-2xl font-bold text-center">Login</h1>
        <form action={loginUser} className="space-y-4">
          <div>
            <label htmlFor="email">Email</label>
            <input id="email" name="email" type="email" required className="w-full p-2 border rounded" />
          </div>
          <div>
            <label htmlFor="password">Password</label>
            <input id="password" name="password" type="password" required className="w-full p-2 border rounded" />
          </div>
          <button type="submit" className="w-full p-2 text-white bg-blue-600 rounded hover:bg-blue-700">
            Login
          </button>
        </form>
      </div>
    </main>
  );
}

Now, add the loginUser action to your actions.ts file. Notice it's almost identical to registerUser, but it redirects to the dashboard on success.

app/lib/actions.ts (add this function):

// app/lib/actions.ts

// ... existing registerUser function

import { cookies } from 'next/headers'; // Add this import

export async function loginUser(formData: FormData) {
  const email = formData.get('email');
  const password = formData.get('password');

  try {
    const response = await fetch(`${API_URL}/api/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    });

    if (!response.ok) {
      throw new Error('Login failed');
    }

    // The 'Set-Cookie' headers from the backend are automatically
    // passed to the browser. The `fetch` API and Next.js handle this.

  } catch (error) {
    console.error(error);
    // Handle error
    return; // Early return on failure
  }
  
  // Redirect to a protected route on success
  redirect('/dashboard');
}

Step 3: Verifying the Session and Protecting Routes

Now that the user can log in, we need a way to check if they are authenticated and protect routes like /dashboard. We'll use a combination of a server-side session utility and Next.js Middleware.

app/lib/session.ts:

// app/lib/session.ts
import 'server-only';
import { cookies } from 'next/headers';
import { jwtVerify } from 'jose';

const secretKey = new TextEncoder().encode(process.env.JWT_SECRET_KEY); // Use the same secret as your backend

interface UserPayload {
  sub: string; // email
  name: string;
  roles: string[];
  iat: number;
  exp: number;
}

export async function verifySession() {
  const cookieStore = cookies();
  const token = cookieStore.get('accessToken')?.value;

  if (!token) {
    return null;
  }

  try {
    const { payload } = await jwtVerify(token, secretKey, {
        algorithms: ['HS256'],
    });
    return payload as UserPayload;
  } catch (error) {
    console.log('Failed to verify session:', error);
    return null;
  }
}

Note: For jwtVerify to work, you'll need to install jose: npm install jose. Also, ensure you have the JWT_SECRET_KEY in your .env.local file, matching the one used in your Spring Boot backend.

middleware.ts (create this in the root of your project, next to app):

// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { verifySession } from './app/lib/session';

const protectedRoutes = ['/dashboard'];

export async function middleware(req: NextRequest) {
  const path = req.nextUrl.pathname;
  const isProtectedRoute = protectedRoutes.some(route => path.startsWith(route));

  if (isProtectedRoute) {
    const session = await verifySession();
    if (!session) {
      // Redirect to login if not authenticated
      const url = req.nextUrl.clone();
      url.pathname = '/login';
      return NextResponse.redirect(url);
    }
  }

  return NextResponse.next();
}

// See "Matching Paths" below to learn more
export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

This middleware checks for the session cookie on protected routes and redirects unauthenticated users to the login page. The official Next.js documentation on Authentication provides more detail on this pattern.

Step 4: Dashboard and Logout

Finally, let's create the protected dashboard page that displays user information and a logout button.

app/dashboard/page.tsx:

// app/dashboard/page.tsx
import { verifySession } from "@/app/lib/session";
import { logoutUser } from "@/app/lib/actions";

export default async function DashboardPage() {
  const session = await verifySession();

  return (
    <div className="p-8">
      <h1 className="text-3xl font-bold">Dashboard</h1>
      <p className="mt-4">Welcome, {session?.name}!</p>
      <p>Your email: {session?.sub}</p>
      <p>Your roles: {session?.roles.join(', ')}</p>
      
      <form action={logoutUser} className="mt-6">
        <button type="submit" className="px-4 py-2 text-white bg-red-600 rounded hover:bg-red-700">
          Logout
        </button>
      </form>
    </div>
  );
}

Now, add the logoutUser action. For our stateless setup, logging out on the client simply means deleting the cookies.

app/lib/actions.ts (add this function):

// app/lib/actions.ts

// ... existing code

export async function logoutUser() {
  const cookieStore = cookies();
  cookieStore.delete('accessToken');
  cookieStore.delete('refreshToken');
  
  redirect('/login');
}

4. Putting It All Together

You have now built a complete authentication flow. Run your Next.js application:

npm run dev

Open your browser to http://localhost:3000 and test the entire user journey:

  1. Navigate to /register and create a new account.
  2. You should be redirected to /login.
  3. Log in with the new credentials.
  4. You should be redirected to /dashboard, where you see your user information.
  5. Click the logout button, which should return you to the /login page.
  6. Try to access /dashboard directly; the middleware should redirect you to /login.

This flow is running against your live EKS cluster, validating the entire system you've built from the database up to the user's browser.

Kubernetes External Traffic Flow with NGINX Ingress Controller
This diagram visualizes our complete architecture. Your Next.js app (the "client") makes requests that travel through an AWS Load Balancer and Ingress to reach the Spring Boot services running in your EKS cluster.

Conclusion and Course Wrap-Up

Congratulations! You have successfully built and integrated a minimal Next.js frontend with your secure, cloud-native Spring Boot application. This final lesson closes the loop on our project, demonstrating a full, end-to-end user flow.

Key Takeaways from this Lesson:

  • HTTP-only cookies are the standard for securely storing authentication tokens in web applications, protecting against XSS attacks.
  • The Next.js App Router enables powerful, server-centric authentication patterns using Server Actions for mutations, server-side functions for session validation, and Middleware for route protection.
  • You have successfully connected a client application to a backend deployed on Kubernetes, a crucial skill for modern full-stack and backend engineers.

Course Review:
Over the past 12 modules, you've gone from the basics of Java to deploying a sophisticated, production-style application. You've learned Spring Boot, built a REST API, implemented secure authentication, handled data persistence with JPA, written comprehensive tests, containerized services with Docker, and orchestrated them on AWS with Kubernetes.

You now have a complete, hands-on project that showcases a broad and deep set of skills sought after in the industry. This blog platform is not just a demo; it's a blueprint for building robust, scalable backend systems. Well done on completing this journey