No articles found
Try different keywords or browse our categories
Fix: Next.js App Router API route not working error
Quick fix for Next.js App Router API route not working error. Learn how to properly create and use API routes in the App Router.
The ‘Next.js App Router API route not working’ error occurs when developers have issues with API routes in the App Router structure. This can happen due to incorrect file placement, wrong export patterns, or misunderstanding the new API route structure in the app directory.
How the Error Happens
❌ Error Scenario - Wrong File Location:
// ❌ This won't work in App Router
// pages/api/data.js - ❌ Old Pages Router location
export default function handler(req, res) {
res.status(200).json({ message: 'Hello' });
}
❌ Error with Wrong Export Pattern:
// ❌ This won't work in App Router
// app/api/data/route.js
export default function apiHandler(req, res) {
// ❌ Old Pages Router pattern
res.status(200).json({ message: 'Hello' });
}
❌ Error with Missing HTTP Methods:
// ❌ This won't work properly
// app/api/data/route.js
// ❌ Missing HTTP method exports
export default function handler() {
return new Response(JSON.stringify({ message: 'Hello' }));
}
✅ Quick Fix - Proper API Route Structure
Solution 1: Correct API Route Structure
// ✅ Proper API route in App Router
// app/api/data/route.js
import { NextResponse } from 'next/server';
export async function GET(request) {
return NextResponse.json({
message: 'Hello from API route',
timestamp: new Date().toISOString()
});
}
export async function POST(request) {
const body = await request.json();
return NextResponse.json({
message: 'Data received',
received: body
});
}
Solution 2: Advanced API Route with Parameters
// ✅ API route with dynamic segments
// app/api/users/[id]/route.js
import { NextResponse } from 'next/server';
export async function GET(request, { params }) {
const { id } = params;
// Simulate fetching user data
const user = {
id,
name: `User ${id}`,
email: `user${id}@example.com`
};
return NextResponse.json(user);
}
export async function PUT(request, { params }) {
const { id } = params;
const body = await request.json();
// Simulate updating user
return NextResponse.json({
id,
...body,
message: 'User updated'
});
}
export async function DELETE(request, { params }) {
const { id } = params;
// Simulate deleting user
return NextResponse.json({
message: `User ${id} deleted`
});
}
Solution 3: API Route with Query Parameters
// ✅ API route handling query parameters
// app/api/search/route.js
import { NextResponse } from 'next/server';
export async function GET(request) {
const { searchParams } = new URL(request.url);
const query = searchParams.get('q');
const limit = searchParams.get('limit') || 10;
if (!query) {
return NextResponse.json(
{ error: 'Query parameter "q" is required' },
{ status: 400 }
);
}
// Simulate search results
const results = Array.from({ length: parseInt(limit) }, (_, i) => ({
id: i + 1,
title: `${query} result ${i + 1}`,
url: `/results/${i + 1}`
}));
return NextResponse.json({ results, query });
}
Solution 4: API Route with Error Handling
// ✅ API route with proper error handling
// app/api/products/[id]/route.js
import { NextResponse } from 'next/server';
export async function GET(request, { params }) {
try {
const { id } = params;
// Validate ID
if (!id || isNaN(id)) {
return NextResponse.json(
{ error: 'Valid product ID is required' },
{ status: 400 }
);
}
// Simulate fetching product
const product = {
id: parseInt(id),
name: `Product ${id}`,
price: Math.random() * 100,
inStock: true
};
if (!product) {
return NextResponse.json(
{ error: 'Product not found' },
{ status: 404 }
);
}
return NextResponse.json(product);
} catch (error) {
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
Solution 5: Using Server Actions Instead of API Routes
// ✅ Alternative: Server Actions for data mutations
// app/actions.js
'use server';
import { revalidatePath } from 'next/cache';
export async function createPost(title, content) {
// Simulate creating a post
const newPost = {
id: Date.now(),
title,
content,
createdAt: new Date().toISOString()
};
// Revalidate the posts page
revalidatePath('/posts');
return newPost;
}
export async function updatePost(id, updates) {
// Simulate updating a post
const updatedPost = {
id: parseInt(id),
...updates,
updatedAt: new Date().toISOString()
};
revalidatePath(`/posts/${id}`);
return updatedPost;
}
// ✅ Using Server Action in Client Component
// components/CreatePostForm.js
'use client';
import { createPost } from '../actions';
export default function CreatePostForm() {
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const title = formData.get('title');
const content = formData.get('content');
await createPost(title, content);
e.target.reset();
};
return (
<form onSubmit={handleSubmit}>
<input
name="title"
placeholder="Title"
required
/>
<textarea
name="content"
placeholder="Content"
required
/>
<button type="submit">Create Post</button>
</form>
);
} Related Articles
Fix: getServerSideProps is not supported in App Router Next.js error - Complete Guide
Complete guide to fix 'getServerSideProps is not supported in App Router' error in Next.js applications. Learn how to migrate from Pages Router to App Router and implement server-side rendering with the new API.
Fix: cookies() can only be used in Server Components error Next.js
Quick fix for 'cookies() can only be used in Server Components' error in Next.js. Learn how to properly use cookies in Server Components.
Fix: document is not defined in Next.js Error - Complete Client-Side Guide
Complete guide to fix 'document is not defined' error in Next.js applications. Learn how to handle browser APIs safely in server-side rendering environments.