Skip to main content

Welcome to a Grasp lesson

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

Lesson 80

Publishing a Blog Post in Next.js: An End-to-End Walkthrough

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

Welcome back for our final lesson!

In our last session, you brilliantly connected the frontend to the backend by building a secure authentication UI with Next.js. You implemented registration, login, and logout flows that interact directly with our Spring Boot services running live on your EKS cluster. This was a massive step, proving the core of our distributed system works as intended.

Today, we complete the picture. The goal for this final lesson is to create and publish a blog post from the Next.js UI, verifying the entire request flow through Ingress, Gateway, and backend services. This is the capstone activity that ties together every single module of this course, from frontend interaction to database persistence in the cloud.

We'll build the final piece of UI, but more importantly, we'll focus on tracing and debugging the request path through our production-style environment. You'll use professional tooling to gain visibility into the system, culminating in a live debugging session where you'll intercept traffic from your EKS cluster and hit a breakpoint in your local IDE.

Let's build and verify the final user story of our blog platform.

1. Building the "Create Post" UI

First, we need a simple interface for writing a blog post. This will be a protected route, accessible only after logging in.

  1. Create a new file at app/dashboard/create/page.tsx.

  2. Add a simple link to your dashboard page (app/dashboard/page.tsx) so you can navigate to it.

    // In app/dashboard/page.tsx, add this link
    import Link from 'next/link';
    
    // ... inside the component's return statement
    <Link href="/dashboard/create" className="text-blue-500 hover:underline mt-4 inline-block">
        Create New Post
    </Link>
    
  3. Now, implement the create post form. This will follow the same pattern as our login/register forms, using a Server Action to handle the submission.

    app/dashboard/create/page.tsx:

    // app/dashboard/create/page.tsx
    import { createPost } from "@/app/lib/actions";
    
    export default function CreatePostPage() {
      return (
        <main className="p-8">
          <h1 className="text-3xl font-bold mb-6">Create a New Post</h1>
          <form action={createPost} className="space-y-4 max-w-2xl">
            <div>
              <label htmlFor="title" className="block text-sm font-medium text-gray-700">Title</label>
              <input
                id="title"
                name="title"
                type="text"
                required
                className="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
              />
            </div>
            <div>
              <label htmlFor="content" className="block text-sm font-medium text-gray-700">Content</label>
              <textarea
                id="content"
                name="content"
                rows={10}
                required
                className="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
              ></textarea>
            </div>
            <button
              type="submit"
              className="px-4 py-2 font-bold text-white bg-blue-600 rounded-md hover:bg-blue-700"
            >
              Publish Post
            </button>
          </form>
        </main>
      );
    }
    

This simple React component renders a form that, on submission, will invoke the createPost Server Action.


2. Implementing the Authenticated Server Action

Now for the logic. The createPost action needs to send an authenticated request to our blog-service. In our architecture, "authenticated" means forwarding the JWT stored in the accessToken cookie.

Since a Next.js Server Action runs on the server, it acts as a middleman. It receives the request from the browser (with cookies), and then it must create a new request to our Spring Boot backend, making sure to pass the authentication token along.

Let's implement this in app/lib/actions.ts.

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

import { redirect } from 'next/navigation';
import { cookies } from 'next/headers';
import { revalidatePath } from 'next/cache';

const API_URL = process.env.API_BASE_URL;

// ... existing registerUser, loginUser, logoutUser functions

export async function createPost(formData: FormData) {
  const title = formData.get('title');
  const content = formData.get('content');

  const cookieStore = cookies();
  const accessToken = cookieStore.get('accessToken')?.value;

  if (!accessToken) {
    // This should ideally not happen if middleware is set up correctly
    redirect('/login');
  }

  try {
    const response = await fetch(`${API_URL}/api/blog/posts`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // Forward the cookie to the backend API
        'Cookie': `accessToken=${accessToken}`
      },
      body: JSON.stringify({ title, content }),
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || 'Failed to create post');
    }

  } catch (error) {
    console.error('Error creating post:', error);
    // Handle error appropriately in a real app
    return;
  }

  // Revalidate the path to show the new post on the blog page
  revalidatePath('/blog');
  // Redirect to the blog page to see the new post
  redirect('/blog');
}

This completes the logic for creating a post. Notice two key Next.js functions:

  • revalidatePath('/blog'): This tells Next.js to purge its cache for the /blog page, ensuring that the next time a user visits, it will be re-rendered with the new post included.
  • redirect('/blog'): This sends the user to the main blog feed after their post is successfully published.

3. Viewing All Posts

To see the fruits of our labor, we need a public page that lists all blog posts.

  1. Create app/blog/page.tsx. This will serve as our main blog feed.

  2. Implement it as a Server Component that fetches data directly from our blog-service.

    app/blog/page.tsx:

    // app/blog/page.tsx
    
    const API_URL = process.env.API_BASE_URL;
    
    async function getPosts() {
      try {
        // This is a server-side fetch, running on the Next.js server
        const res = await fetch(`${API_URL}/api/blog/posts`, {
          // Use 'no-store' to ensure we get fresh data on every request
          // In a real-world app, you might use time-based revalidation.
          cache: 'no-store', 
        });
    
        if (!res.ok) {
          throw new Error('Failed to fetch posts');
        }
        return res.json();
      } catch (error) {
        console.error('Error fetching posts:', error);
        return [];
      }
    }
    
    interface Post {
      id: string;
      title: string;
      content: string;
      authorName: string;
      createdAt: string;
    }
    
    export default async function BlogPage() {
      const posts: Post[] = await getPosts();
    
      return (
        <main className="p-8">
          <h1 className="text-4xl font-bold mb-8">The Blog</h1>
          <div className="space-y-8">
            {posts.length > 0 ? (
              posts.map((post) => (
                <article key={post.id} className="p-6 border rounded-lg shadow-sm">
                  <h2 className="text-2xl font-semibold text-blue-800">{post.title}</h2>
                  <p className="text-sm text-gray-500 mt-1">By {post.authorName} on {new Date(post.createdAt).toLocaleDateString()}</p>
                  <p className="mt-4 text-gray-700">{post.content.substring(0, 200)}...</p>
                </article>
              ))
            ) : (
              <p>No posts yet. Go write one!</p>
            )}
          </div>
        </main>
      );
    }
    

With this in place, we have a complete loop: create, publish, and view.


4. Verifying the End-to-End Flow

This is the most critical part of the lesson. We'll now trace a request all the way from your browser to the database and back.

Part A: The "Happy Path" Log Trace

  1. In separate terminals, start tailing the logs for your key services running in EKS. You can get the pod names with kubectl get pods.

    
    
    
    # Terminal 1: API Gateway
    kubectl logs -f <your-gateway-service-pod-name>
    
    
    
    
    # Terminal 2: Blog Service
    kubectl logs -f <your-blog-service-pod-name>
    
  2. Open your browser, log into the application, and navigate to the "Create New Post" page.

  3. Fill out the title and content, then click "Publish Post".

  4. Observe the logs:

    • You should see a POST /api/blog/posts request hit the API Gateway.
    • The gateway will forward this, and you'll see a log in the blog-service indicating that the createPost endpoint was called and a new post was created.
  5. Your browser will be redirected to /blog, where you should see your newly published post.

This confirms that the entire chain—Ingress, Gateway, Blog Service, and Database—is working correctly.

Part B: Remote Debugging with Telepresence

Tracing logs is good, but what if you need to debug complex logic? The "build, push, deploy" cycle is painfully slow. This is where Telepresence becomes your superpower. It creates a network bridge between your local machine and the Kubernetes cluster, allowing you to "intercept" traffic meant for a service in the cluster and redirect it to your local development machine.

Debugging Java Microservices "Remocally" in Kubernetes with Telepresence by Daniel Bryant

To understand how this works, watch this excellent explanation by Daniel Bryant from Devoxx UK. It perfectly illustrates the problem Telepresence solves and how it works.

Watch the following sections: The Problem (00:47 - 01:16): Understand why the inner development loop is slow with microservices and Kubernetes. How Telepresence Works (08:53 - 13:30): This is the core concept. Pay close attention to the diagrams showing how traffic is intercepted and routed from the remote cluster to the local machine. Live Demo (13:30 - 19:45): See a practical demonstration of intercepting a service and hitting a local breakpoint. This is exactly what you are about to do.

Now, let's do it yourself.

Step 1: Install and Connect Telepresence

If you're on macOS with Homebrew, installation is simple.

brew install datawire/blackbird/telepresence

(For other operating systems, follow the official Telepresence documentation.)

Now, connect your laptop to your EKS cluster's network.

telepresence connect

You'll be prompted to install the traffic manager in your cluster. Say yes. Once connected, your machine can resolve services within the cluster as if it were another pod (e.g., you could run curl http://blog-service:8080/api/blog/posts).

Step 2: Intercept the Blog Service

Tell Telepresence to intercept traffic for the blog-service and forward it to your local machine on port 8080.

telepresence intercept blog-service --port 8080

Your terminal will now show that all traffic destined for blog-service inside EKS is being routed to localhost:8080.

Step 3: Hit a Local Breakpoint

  1. Open the blog platform project in IntelliJ IDEA.
  2. Navigate to the PostController in the blog-service module.
  3. Set a breakpoint on the first line inside your createPost method.
  4. Run the blog-service locally in Debug Mode. Your local instance will start up on port 8080.
  5. Go back to your Next.js application in the browser and publish another blog post.
  6. Magic! The execution will pause at the breakpoint inside your local IntelliJ IDEA instance.
Microservices Architecture Request Flow
This diagram shows the high-level request flow. With Telepresence, you've essentially swapped the 'Microservice B' pod in the cluster with the instance running on your laptop, allowing you to debug it live.

You can now inspect the incoming request, the DTO, the authenticated Principal object passed by Spring Security, and step through your business logic line by line—all while interacting with the other real services, database, and message queue running in your remote EKS cluster. This is an incredibly powerful and efficient workflow for a backend developer.

When you're finished debugging, press Ctrl+C in the Telepresence terminal to stop the intercept.


Course Conclusion

Congratulations! You have officially completed the final lesson and the entire course.

You have not just learned a technology; you have built a complete, end-to-end, production-style system. You started with zero Java knowledge and have progressed to architecting, building, testing, and deploying a secure, cloud-native microservices application.

Let's reflect on what you've accomplished:

  • Mastered Spring Boot: From IoC and Dependency Injection to building robust REST APIs with Spring MVC, JPA, and Spring Security.
  • Built a Secure Backend: Implemented industry-grade authentication with JWTs, refresh tokens, and role-based access control.
  • Designed for Scale: Containerized your services with Docker and orchestrated them on a real Kubernetes cluster (AWS EKS).
  • Automated Everything: Designed a CI/CD pipeline to automatically test, build, and deploy your code.
  • Gained Full-Stack Insight: Connected a modern Next.js frontend, completing the user-facing experience.
  • Learned to Debug Like a Pro: Mastered debugging techniques from reading stack traces to using advanced tools like Testcontainers and Telepresence.

The project you've built is a powerful portfolio piece and, more importantly, a testament to the deep, practical skills you now possess. You have the foundation to confidently tackle complex backend challenges and build scalable, resilient systems. This is the skillset of a modern Senior Backend and Platform Engineer.

Well done on this incredible achievement. Your dedication has paid off.