How can i share logics between several route handlers in NextJS 13 app router?

56 views Asked by At

I'm trying to create APIs using route handlers in a Next.js 13 app.

Some of these APIs need to read cookies and handle logic to respond with errors if the user is not logged in or if the login has expired. This logic is common to many APIs, and I'd like to handle it in one central place, similar to how layout.js or layout.tsx can be shared across multiple pages.

Is there a feature in route handlers that can perform a role similar to layouts?

This doesn't seem to be covered in the official documentation. Is there another clean way to address the problem I'm facing?

Using middleware seems like a possible solution. However, checking all URLs for all APIs in 'single' middleware file and performing specific logic for certain APIs doesn't seem like a clean approach for maintenance.

1

There are 1 answers

0
Lee KyuSung On

I wrapped my route handler as nyarthan commented.

src/app/api/~~~/route.ts

import withAuth from "@/libs/server/withAuth";

export async function POST(
  request: Request,
  { params }: { params: { id: string } }
) {
  return withAuth(async (session) => {

    ~~~ logic

    return new Response(
      JSON.stringify({
        ok: true,
      }),
      {
        status: 200,
      }
    );
  });
}

src/libs/server/withAuth.ts

import { Session, User } from "@prisma/client";
import getServerSession from "./getServerSession";
import { NextResponse } from "next/server";

interface SessionWithUser extends Session {
  user: User;
}

export default async function withAuth(
  handler: (session: SessionWithUser) => Promise<Response | NextResponse>
) {
  const session = await getServerSession();
  if (!session) {
    return new Response(
      JSON.stringify({
        ok: false,
        error: "Not logged in",
      }),
      {
        status: 401,
      }
    );
  }

  return handler(session);
}