جاري التحميل...
جاري التحميل...
Route Handlers، proxy.ts، إعادة التوجيه
Route Handlers هي الطريقة لإنشاء نقاط نهاية API داخل تطبيقات Next.js باستخدام App Router. أنشئ ملف route.js داخل أي مجلد.
Route Handlers تعمل فقط على الخادم — لا يُحمّل أي JavaScript إلى العميل.
GET — جلب البياناتPOST — إنشاء بياناتPUT — تحديث البياناتDELETE — حذف البياناتفي Next.js 16، proxy.ts يحل محل الـ Middleware القديم. يتعامل مع تعديل الطلب/الاستجابة، والمصادقة، وإعادة التوجيه.
أي ملف ينشئ نقطة نهاية API في App Router؟
أين تنفذ Route Handlers؟
أنشئ route handlers GET و POST لنقطة نهاية users API.
الحل:
// 1. ملف app/api/todos/route.js
import { NextResponse } from "next/server";
let todos = [
{ id: "1", title: "تعلم Next.js", completed: false },
{ id: "2", title: "بناء مشروع", completed: false },
];
// GET /api/todos
export async function GET() {
return NextResponse.json({ success: true, data: todos });
}
// POST /api/todos
export async function POST(request) {
try {
const body = await request.json();
if (!body.title) {
return NextResponse.json(
{ success: false, error: "العنوان مطلوب" },
{ status: 400 }
);
}
const newTodo = {
id: String(todos.length + 1),
title: body.title,
completed: false,
};
todos.push(newTodo);
return NextResponse.json({ success: true, data: newTodo }, { status: 201 });
} catch (error) {
return NextResponse.json(
{ success: false, error: "بيانات غير صحيحة" },
{ status: 400 }
);
}
}
// 2. ملف app/api/todos/[id]/route.js
export async function GET(request, { params }) {
const { id } = await params;
const todo = todos.find((t) => t.id === id);
if (!todo) {
return NextResponse.json({ success: false, error: "غير موجود" }, { status: 404 });
}
return NextResponse.json({ success: true, data: todo });
}
export async function PUT(request, { params }) {
const { id } = await params;
const body = await request.json();
const index = todos.findIndex((t) => t.id === id);
if (index === -1) {
return NextResponse.json({ success: false, error: "غير موجود" }, { status: 404 });
}
todos[index] = { ...todos[index], ...body, id };
return NextResponse.json({ success: true, data: todos[index] });
}
export async function DELETE(request, { params }) {
const { id } = await params;
const index = todos.findIndex((t) => t.id === id);
if (index === -1) {
return NextResponse.json({ success: false, error: "غير موجود" }, { status: 404 });
}
todos.splice(index, 1);
return NextResponse.json({ success: true, message: "تم الحذف" });
}
// 3. ملف proxy.ts
import { NextResponse } from "next/server";
const protectedPaths = ["/dashboard", "/admin"];
export function proxy(request) {
const { pathname } = request.nextUrl;
const isProtected = protectedPaths.some((path) => pathname.startsWith(path));
if (isProtected) {
const token = request.cookies.get("auth-token");
if (!token) {
return NextResponse.redirect(new URL("/login", request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*", "/api/:path*"],
};معالج GET:
export async function GET(request) {
const data = await fetchData();
return Response.json(data);
}معالج POST:
export async function POST(request) {
const body = await request.json();
const result = await createItem(body);
return Response.json(result, { status: 201 });
}معالج مسار ديناميكي:
export async function GET(request, { params }) {
const { id } = await params;
const item = await getItem(id);
return Response.json(item);
}الـ Proxy:
import { NextResponse } from "next/server";
export function proxy(request) {
if (!request.cookies.get("token")) {
return NextResponse.redirect(
new URL("/login", request.url)
);
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"],
};ما هو route handler؟
الإجابة:
ملف route.js في مجلد app يوفر API endpoint.
كيف تحمي route؟
الإجابة:
استخدم middleware.ts أو تحقق من Session في Route Handler.
استخدم middleware
للحماية التلقائية للمسارات قبل الوصول لها