Image

Middlewares

미들웨어가 /pages/_middleware.ts에 생성된 경우 /pages 디렉토리 내의 모든 경로에서 실행됩니다.

import type { NextRequest, NextFetchEvent } from "next/server";
export function middleware(req: NextRequest, ev: NextFetchEvent) {
  console.log(req.ua);
}

쿠키, bot 등에 따라 redirect 할 수 있다.

import type { NextRequest, NextFetchEvent } from "next/server";
import { NextResponse } from "next/server";

export function middleware(req: NextRequest, ev: NextFetchEvent) {
  if (req.ua?.isBot) {
    return new Response("Plz don't be a bot. Be human.", { status: 403 });
  }
  if (!req.url.includes("/api")) {
    if (!req.url.includes("/enter") && !req.cookies.carrotsession) {
      return NextResponse.redirect("/enter");
    }
  }
  //  return NextResponse.json({ ok: true });
}
import type { NextFetchEvent, NextRequest } from 'next/server';
import { NextResponse } from 'next/server';

const RESTRICT_ROUTES = ['/login', '/register'];

export const middleware = (req: NextRequest, ev: NextFetchEvent) => {
  if (req.ua?.isBot) {
    return new Response('미치셨습니까 휴먼?', { status: 403 });
  }

  const pagename = req.page.name;
  const isAPI = req.url.includes('/api');
  if (isAPI || !pagename) return;

  const hasSession = !!req.cookies.mildvu_session;
  const isRestrictRoute = RESTRICT_ROUTES.some((route) => route === pagename);
  const isPrivateRoute = pagename.includes('/me');

  if (hasSession && isRestrictRoute) {
    return NextResponse.redirect(new URL(`/me`, req.url));
  }

  if (!hasSession && isPrivateRoute) {
    return NextResponse.redirect(new URL('/login', req.url));
  }
};