Creating API Routes with Next.js and Authentication

Let's dive into creating API routes with Next.js and ensuring they are authenticated using auth() function.

  • Create API Endpoint: Define your API endpoint logic in a separate file within the pages/api directory.
  • /app/api/user/route.tsx
    1 import { NextRequest, NextResponse } from 'next/server';
    2 export const GET = async (request: NextRequest) => {
    3    .....
    4    return new NextResponse();
    5  }
  • Wrap with Authentication: Use Auth.js auth() function to authenticate your API routes. This ensures that only authenticated users can access them.
  • /app/api/example/route.tsx
    1 import { NextRequest, NextResponse } from 'next/server';
    2 import { auth } from '@/lib/next-auth';
    3 export const POST = auth(async (request: NextRequest) => {
    4    .....
    5    return new NextResponse();
    6  });
For more detailed information, check out the official documentation nextjs | auth.js