๐Ÿ“ฆ cloudflare / vinext

๐Ÿ“„ route.ts ยท 52 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52import { NextResponse, after } from "next/server";
import { cookies } from "next/headers";
import { revalidateTag } from "next/cache";

// GET โ€” returns JSON with request info
export async function GET(request: Request) {
  const url = new URL(request.url);
  const name = url.searchParams.get("name") ?? "world";

  return NextResponse.json({
    message: `Hello, ${name}! From vinext with nitro.`,
    pathname: url.pathname,
    runtime:
      typeof globalThis.navigator !== "undefined"
        ? (globalThis.navigator as { userAgent?: string }).userAgent
        : "unknown",
    timestamp: new Date().toISOString(),
  });
}

// POST โ€” demonstrates mutation with cookies and after()
export async function POST(request: Request) {
  const body = await request.json().catch(() => ({}));
  const { action } = body as { action?: string };

  const c = await cookies();

  if (action === "increment-visits") {
    const current = Number.parseInt(c.get("visit-count")?.value ?? "0", 10);
    c.set("visit-count", String(current + 1), { path: "/" });
  }

  if (action === "set-theme") {
    const { theme } = body as { theme?: string };
    c.set("theme", theme ?? "light", { path: "/" });
  }

  // after() โ€” run work after the response is sent
  after(() => {
    console.log(`[after] POST /api/hello action=${action}`);
  });

  return NextResponse.json({ ok: true, action });
}

// DELETE โ€” demonstrates revalidation
export async function DELETE() {
  revalidateTag("blog-posts");

  return NextResponse.json({ ok: true, revalidated: "blog-posts" });
}