超越前端
Next.js 通常被认为是构建 UI 的 React 框架,但它实际上是一个完整的全栈平台。您可以在单个 Next.js 项目中构建从数据库到浏览器的整个应用。
API 路由与路由处理器
App Router 提供了路由处理器,让您使用标准 Web API 创建 API 端点:
// app/api/posts/route.ts
export async function GET() {
const posts = await db.post.findMany();
return Response.json(posts);
}
export async function POST(request: Request) {
const body = await request.json();
const post = await db.post.create({ data: body });
return Response.json(post, { status: 201 });
}
服务端操作
服务端操作允许您直接从组件中调用服务端函数,无需创建单独的 API 路由:
// app/actions.ts
"use server";
import { revalidatePath } from "next/cache";
export async function createPost(formData: FormData) {
const title = formData.get("title") as string;
await db.post.create({ data: { title } });
revalidatePath("/posts");
}
// 客户端组件
"use client";
import { createPost } from "./actions";
export function NewPostForm() {
return (
);
}
中间件
中间件在请求完成之前运行。用于身份验证、重定向、A/B 测试等:
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const isAuthenticated = request.cookies.has("token");
if (!isAuthenticated && request.nextUrl.pathname.startsWith("/dashboard")) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: "/dashboard/:path*",
};
综合运用
一个典型的全栈 Next.js 应用可能包括:
所有这些都存在于一个统一的代码库中——无需单独的后端!