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.
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.
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.
// 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 }
)
}
NextReady supports all standard HTTP methods for API routes:
GET
- Retrieve dataPOST
- Create new dataPUT
- Update existing dataPATCH
- Partially update existing dataDELETE
- Delete dataFor 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 }
)
}
NextReady includes a complete authentication system with API routes for user registration, login, and profile management.
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// 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'
})
})
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: '/'
})
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.
NextReady includes a complete blog system with API routes for managing blog posts.
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// Example: Get all blog posts
const response = await fetch('/api/posts')
const posts = await response.json()
// 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
})
})
// 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
})
})
// Example: Delete a blog post
const postId = 'your-post-id'; // Déclaration de la variable
const response = await fetch(`/api/posts/${postId}`, {
method: 'DELETE'
})
NextReady includes API routes for managing contact form submissions.
The following contact API routes are available:
/api/contact
- Submit a contact form or get all contacts// 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...'
})
})
// Example: Get all contacts (requires admin authentication)
const response = await fetch('/api/contact')
const contacts = await response.json()
NextReady includes API routes for handling payments and subscriptions with Stripe.
The following payment API routes are available:
/api/checkout
- Create a checkout session/api/payments
- Get payment information/api/webhooks/stripe
- Handle Stripe webhooks// 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
When working with Stripe webhooks, ensure that the payment status checks are looking for succeeded
status (not completed
) to avoid payment processing issues.
NextReady includes API routes for managing user profiles and settings.
The following user API routes are available:
/api/users
- Get all users or update the current user// 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'
})
})
NextReady includes webhook handlers for integrating with external services.
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 })
To set up webhooks for your application:
https://yourdomain.com/api/webhooks/stripe
You can easily extend NextReady with your own custom API routes.
To create a new API route:
src/app/api
for your route (e.g., src/app/api/custom
)route.ts
file in the directory// 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 }
)
}
}
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*',
}
Now that you understand how to work with API routes in NextReady, you might want to explore: