NextReady

API Routes

NextReady provides a comprehensive set of API routes built with Next.js App Router, allowing you to easily interact with your database and external services.

Overview

NextReady uses Next.js App Router API routes, which are serverless functions that run on-demand. These API routes are located in the src/app/api directory and follow the Next.js App Router conventions.

Key Features

  • Built on Next.js App Router API routes
  • TypeScript support for type safety
  • Authentication and authorization middleware
  • MongoDB integration
  • Error handling and response formatting

Route Handlers

NextReady uses the Next.js App Router route handlers to create API endpoints. These handlers are defined in route.ts files within the src/app/api directory structure.

Basic Route Handler Structure

// src/app/api/example/route.ts
import { NextResponse } from 'next/server'
import dbConnect from '@/lib/mongodb'
import SomeModel from '@/models/SomeModel'

export const dynamic = 'force-dynamic' // Optional: prevents caching

export async function GET(request: Request) {
  try {
    await dbConnect()
    const items = await SomeModel.find({})
    return NextResponse.json(items)
  } catch (error) {
    console.error('API error:', error)
    return NextResponse.json(
      { error: 'Internal Server Error' },
      { status: 500 }
    )
  }
}

export async function POST(request: Request) {
  try {
    const data = await request.json()
    await dbConnect()
    const newItem = await SomeModel.create(data)
    return NextResponse.json(newItem, { status: 201 })
  } catch (error) {
    console.error('API error:', error)
    return NextResponse.json(
      { error: 'Internal Server Error' },
      { status: 500 }
    )
  }

Available HTTP Methods

NextReady supports all standard HTTP methods for API routes:

  • GET - Retrieve data
  • POST - Create new data
  • PUT - Update existing data
  • PATCH - Partially update existing data
  • DELETE - Delete data

Dynamic Routes

For routes that need to handle dynamic parameters, NextReady uses the Next.js dynamic route segments:

// src/app/api/posts/[id]/route.ts
import { NextResponse } from 'next/server'
import dbConnect from '@/lib/mongodb'
import Post from '@/models/Post'

export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    await dbConnect()
    const post = await Post.findById(params.id)
    
    if (!post) {
      return NextResponse.json(
        { error: 'Post not found' },
        { status: 404 }
      )
    }
    
    return NextResponse.json(post)
  } catch (error) {
    console.error('API error:', error)
    return NextResponse.json(
      { error: 'Internal Server Error' },
      { status: 500 }
    )
  }

Authentication API

NextReady includes a complete authentication system with API routes for user registration, login, and profile management.

Authentication Routes

The following authentication routes are available:

  • /api/auth/[...nextauth] - NextAuth.js API routes for authentication
  • /api/auth/signup - User registration endpoint
  • /api/admin-auth - Admin authentication endpoint

User Registration

// Example request to register a new user
const response = await fetch('/api/auth/signup', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'John Doe',
    email: 'john@example.com',
    password: 'securepassword'
  })
})

Authentication with NextAuth.js

NextReady uses NextAuth.js for authentication. You can use the NextAuth.js API routes for login, logout, and session management:

// Example: Sign in with credentials
import { signIn } from 'next-auth/react'

await signIn('credentials', {
  email: 'user@example.com',
  password: 'password',
  redirect: false
})

// Example: Sign in with Google
await signIn('google', {
  callbackUrl: '/dashboard'
})

// Example: Sign out
import { signOut } from 'next-auth/react'

await signOut({
  callbackUrl: '/'
})

Dependency Conflict Note

NextReady has a known dependency conflict between next-auth, @auth/core and @auth/mongodb-adapter. To resolve this, make sure to add a .npmrc file with legacy-peer-deps=true to your project.

Blog API

NextReady includes a complete blog system with API routes for managing blog posts.

Blog Routes

The following blog API routes are available:

  • /api/posts - Get all posts or create a new post
  • /api/posts/[id] - Get, update, or delete a specific post

Get All Posts

// Example: Get all blog posts
const response = await fetch('/api/posts')
const posts = await response.json()

Create a New Post

// Example: Create a new blog post
const response = await fetch('/api/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'My New Blog Post',
    content: 'This is the content of my blog post...',
    excerpt: 'A short excerpt for the blog post',
    slug: 'my-new-blog-post',
    coverImage: '/images/blog/my-image.jpg',
    published: true
  })
})

Update a Post

// Example: Update a blog post
const postId = 'your-post-id'; // Déclaration de la variable
const response = await fetch(`/api/posts/${postId}`, {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'Updated Title',
    content: 'Updated content...'
    // Include other fields you want to update
  })
})

Delete a Post

// Example: Delete a blog post
const postId = 'your-post-id'; // Déclaration de la variable
const response = await fetch(`/api/posts/${postId}`, {
  method: 'DELETE'
})

Contact API

NextReady includes API routes for managing contact form submissions.

Contact Routes

The following contact API routes are available:

  • /api/contact - Submit a contact form or get all contacts

Submit Contact Form

// Example: Submit a contact form
const response = await fetch('/api/contact', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'John Doe',
    email: 'john@example.com',
    message: 'Hello, I have a question about your service...'
  })
})

Get All Contacts (Admin Only)

// Example: Get all contacts (requires admin authentication)
const response = await fetch('/api/contact')
const contacts = await response.json()

Payment API

NextReady includes API routes for handling payments and subscriptions with Stripe.

Payment Routes

The following payment API routes are available:

  • /api/checkout - Create a checkout session
  • /api/payments - Get payment information
  • /api/webhooks/stripe - Handle Stripe webhooks

Create a Checkout Session

// Example: Create a checkout session for a subscription
const response = await fetch('/api/checkout', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    priceId: 'price_1234567890',
    successUrl: 'https://yourdomain.com/success',
    cancelUrl: 'https://yourdomain.com/cancel'
  })
})

const { url } = await response.json()
window.location.href = url // Redirect to Stripe Checkout

Stripe Status Check Note

When working with Stripe webhooks, ensure that the payment status checks are looking for succeeded status (not completed) to avoid payment processing issues.

User API

NextReady includes API routes for managing user profiles and settings.

User Routes

The following user API routes are available:

  • /api/users - Get all users or update the current user

Update User Profile

// Example: Update user profile
const response = await fetch('/api/users', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Updated Name',
    image: 'https://example.com/profile-image.jpg'
  })
})

Webhooks

NextReady includes webhook handlers for integrating with external services.

Stripe Webhooks

The Stripe webhook handler is located at /api/webhooks/stripe and processes events from Stripe:

// src/app/api/webhooks/stripe/route.ts
import { NextResponse } from 'next/server'
import { headers } from 'next/headers'
import Stripe from 'stripe'
import { buffer } from 'micro'
import dbConnect from '@/lib/mongodb'
import User from '@/models/User'

export async function POST(request: Request) {
  const body = await request.text()
  const signature = headers().get('stripe-signature')
  
  const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
    apiVersion: '2023-10-16',
  })
  
  let event
  
  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature!,
      process.env.STRIPE_WEBHOOK_SECRET!
    )
  } catch (err) {
    return NextResponse.json(
      { error: 'Webhook signature verification failed' },
      { status: 400 }
    )
  }
  
  // Handle the event
  switch (event.type) {
    case 'checkout.session.completed':
      // Handle completed checkout session
      break
    case 'customer.subscription.created':
      // Handle subscription creation
      break
    case 'customer.subscription.updated':
      // Handle subscription update
      break
    case 'customer.subscription.deleted':
      // Handle subscription deletion
      break
    default:
      console.log(`Unhandled event type: ${event.type}`)
  }
  
  return NextResponse.json({ received: true })

Setting Up Webhooks

To set up webhooks for your application:

  1. Configure the webhook endpoint in the external service (e.g., Stripe Dashboard)
  2. Set the webhook URL to https://yourdomain.com/api/webhooks/stripe
  3. Configure the webhook secret in your environment variables
  4. Implement the webhook handler in your API route

Creating Custom API Routes

You can easily extend NextReady with your own custom API routes.

Creating a New API Route

To create a new API route:

  1. Create a new directory in src/app/api for your route (e.g., src/app/api/custom)
  2. Create a route.ts file in the directory
  3. Implement the HTTP methods you need (GET, POST, etc.)
// src/app/api/custom/route.ts
import { NextResponse } from 'next/server'
import dbConnect from '@/lib/mongodb'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth-config'

export async function GET(request: Request) {
  // Check authentication if needed
  const session = await getServerSession(authOptions)
  if (!session) {
    return NextResponse.json(
      { error: 'Unauthorized' },
      { status: 401 }
    )
  }
  
  // Process the request
  try {
    await dbConnect()
    // Your custom logic here
    
    return NextResponse.json({ success: true, data: 'Your data here' })
  } catch (error) {
    console.error('API error:', error)
    return NextResponse.json(
      { error: 'Internal Server Error' },
      { status: 500 }
    )
  }
}

API Middleware

You can create middleware to handle common tasks like authentication, logging, or error handling:

// src/middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  // Example: Add custom headers to API responses
  if (request.nextUrl.pathname.startsWith('/api/')) {
    const response = NextResponse.next()
    response.headers.set('X-API-Version', '1.0')
    return response
  }
  
  return NextResponse.next()
}

export const config = {
  matcher: '/api/:path*',
}

Next Steps

Now that you understand how to work with API routes in NextReady, you might want to explore: