API Routes
Data & APIs
Preview
Route handlers
A simple API
// app/api/courses/route.js\nexport async function GET() {\n const courses = await fetchCourses();\n return Response.json(courses);\n}POST with validation
// app/api/enroll/route.js\nexport async function POST(request) {\n const body = await request.json();\n if (!body.course_id) {\n return Response.json({ error: "course_id required" }, { status: 400 });\n }\n await enrollUser(body.course_id);\n return Response.json({ ok: true });\n}Environment variables
// .env.local (never commit this!)\nDATABASE_URL="mysql://user:pass@host/db"\nAPI_SECRET="…"Using the API from React
const res = await fetch("/api/enroll", {\n method: "POST",\n headers: { "Content-Type": "application/json" },\n body: JSON.stringify({ course_id: 12 }),\n});Tip: Keep secrets in.env.localonly — anything inprocess.envprefixedNEXT_PUBLIC_is visible in the browser.
This is a free preview lesson
Enroll in the Next.js Development to unlock every lesson, lesson PDF guides, quizzes and your certificate - and start creating your own pieces today.