Understanding Middleware in Next.js (1)

권민재·2025년 2월 14일
0

next

목록 보기
1/1

For session management in a Next.js project using Auth.js or Clerk, middleware is almost essential. However, until now, I have simply copied and pasted the code provided in the documentation into my middleware.ts file without giving much thought to what middleware actually is, why it is used, or what its benefits are.

So today, I am taking the time to deep dive into middleware and explore its purpose and advantages!


1. What is Middleware in Next.js?

Let's start with the official Next.js documentation:

Middleware allows you to run code before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.

In simple terms, middleware intercepts every request, allowing us to add various logic or directly manipulate the request/response.

But what does "request" mean in Next.js?


2. What is Considered a Request in Next.js?

(1) Page Requests

A page request occurs when:

  • A user directly visits /dashboard
  • A user navigates to /dashboard using <Link>
  • A user refreshes the page while on /dashboard

(2) Fetching Data

Requests also occur when fetching data, such as:

  • Calling an API route (app/api/* or pages/api/*)
  • Using Server Actions to fetch data

(3) Does Middleware Run on Re-renders?

Some people mistakenly believe that middleware runs when a component re-renders. However, middleware is NOT triggered by component re-renders.

According to the official Next.js documentation:

Middleware execution is NOT directly triggered by a component re-render. Middleware runs only on incoming HTTP requests from the browser or API calls.

In short, middleware does NOT run when a component re-renders on the client side.


3. When Should You Use Middleware?

Integrating Middleware into your Next.js application can significantly improve performance, security, and user experience. Below are some common use cases:

(1) Authentication and Authorization

  • Middleware can check session cookies in request headers to verify whether the user is authenticated before allowing access to a protected route.

(2) Redirects and Path Rewriting

  • If a user is not logged in, middleware can redirect them to the login page before they reach a protected route.

(3) Logging and Analytics

  • Middleware can capture and analyze request data before processing it in an API or page.

4. Applying Middleware in a Next.js Project

To apply middleware correctly, you must follow two key conventions:
1. The middleware.ts file must be in the root directory of your project.
2. The filename must be exactly middleware.ts or middleware.js.

If your middleware is not working, check these two points first!

Example Middleware Implementation

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/home', request.url));
}

In the example above:

  • Middleware intercepts all requests before they reach the actual page or API route.
  • The function takes a request parameter of type NextRequest.

5. Understanding NextRequest

The NextRequest object extends the Web API Request and provides additional convenience methods.

Analysis of NextRequest

// request.ts
export declare class NextRequest extends Request {
    [INTERNALS]: {
        cookies: RequestCookies;
        url: string;
        nextUrl: NextURL;
    };
    constructor(input: URL | RequestInfo, init?: RequestInit);
    get cookies(): RequestCookies;
    get nextUrl(): NextURL;
    get url(): string;
}

NextRequest is a subclass of Request. It inherits all the standard request properties (headers, body).

export declare class NextRequest extends Request {
  // extends means to inherit all the properties.

But it stores internal metadata related to the Next.js-specific features, such as

  • cookies (to store request cookies)
  • nextUrl (for easier URL handling)
[INTERNALS]: { //Internal is unique key for object properties
        cookies: RequestCookies;
        url: string;
        nextUrl: NextURL;
};

In the next post, we will explore case studies on how middleware is used in each scenario.

profile
퇴사했지만, 코딩은 하고싶어

0개의 댓글

관련 채용 정보