|
| 1 | +// app/api/indexnow/route.ts |
| 2 | +// Next.js App Router API route for IndexNow push (Serverless friendly) |
| 3 | + |
| 4 | +export const runtime = "edge"; // 也可用 "nodejs",两者都能 fetch |
| 5 | + |
| 6 | +type Payload = { |
| 7 | + url?: string; |
| 8 | + urls?: string[]; |
| 9 | + urlList?: string[]; |
| 10 | + host?: string; |
| 11 | + engine?: "bing" | "yandex" | "seznam" | "naver" | "hub"; |
| 12 | +}; |
| 13 | + |
| 14 | +// 可选:简单的调用鉴权,避免被他人滥用。到 Vercel 环境变量里设置 INDEXNOW_API_TOKEN。 |
| 15 | +const REQUIRED_BEARER = process.env.INDEXNOW_API_TOKEN ?? ""; |
| 16 | + |
| 17 | +// 你的 IndexNow 验证 key(即 public/{key}.txt 的文件名部分) |
| 18 | +const INDEXNOW_KEY = |
| 19 | + process.env.INDEXNOW_KEY ?? process.env.NEXT_PUBLIC_INDEXNOW_KEY ?? ""; |
| 20 | + |
| 21 | +function bad(msg: string, status = 400) { |
| 22 | + return new Response(JSON.stringify({ ok: false, error: msg }), { |
| 23 | + status, |
| 24 | + headers: { "content-type": "application/json; charset=utf-8" }, |
| 25 | + }); |
| 26 | +} |
| 27 | + |
| 28 | +function ok(data: unknown) { |
| 29 | + return new Response( |
| 30 | + JSON.stringify({ ok: true, ...((data as object) ?? {}) }), |
| 31 | + { |
| 32 | + status: 200, |
| 33 | + headers: { "content-type": "application/json; charset=utf-8" }, |
| 34 | + }, |
| 35 | + ); |
| 36 | +} |
| 37 | + |
| 38 | +function dedupeValidHttps(urls: (string | undefined)[]) { |
| 39 | + const s = new Set<string>(); |
| 40 | + for (const u of urls) { |
| 41 | + if (!u) continue; |
| 42 | + try { |
| 43 | + const url = new URL(u); |
| 44 | + if (url.protocol === "https:" || url.protocol === "http:") { |
| 45 | + s.add(url.toString()); |
| 46 | + } |
| 47 | + } catch { |
| 48 | + console.error("Invalid URL:", u); |
| 49 | + } |
| 50 | + } |
| 51 | + return [...s]; |
| 52 | +} |
| 53 | + |
| 54 | +function getDefaultHostFromReq(req: Request) { |
| 55 | + // 从请求头推断 Host & Protocol(在 Vercel 上可用) |
| 56 | + const host = |
| 57 | + req.headers.get("x-forwarded-host") ?? req.headers.get("host") ?? ""; |
| 58 | + const proto = req.headers.get("x-forwarded-proto") ?? "https"; |
| 59 | + return { host, proto }; |
| 60 | +} |
| 61 | + |
| 62 | +function endpointFor(engine?: Payload["engine"]) { |
| 63 | + switch (engine) { |
| 64 | + case "bing": |
| 65 | + return "https://www.bing.com/indexnow"; |
| 66 | + case "yandex": |
| 67 | + return "https://yandex.com/indexnow"; |
| 68 | + case "seznam": |
| 69 | + return "https://search.seznam.cz/indexnow"; |
| 70 | + case "naver": |
| 71 | + return "https://searchadvisor.naver.com/indexnow"; |
| 72 | + case "hub": |
| 73 | + default: |
| 74 | + return "https://api.indexnow.org/indexnow"; // 官方 Hub(推荐) |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +async function pushToIndexNow({ |
| 79 | + host, |
| 80 | + key, |
| 81 | + urlList, |
| 82 | + engine, |
| 83 | +}: { |
| 84 | + host: string; |
| 85 | + key: string; |
| 86 | + urlList: string[]; |
| 87 | + engine?: Payload["engine"]; |
| 88 | +}) { |
| 89 | + const keyLocation = `https://${host}/${key}.txt`; |
| 90 | + const endpoint = endpointFor(engine); |
| 91 | + |
| 92 | + const res = await fetch(endpoint, { |
| 93 | + method: "POST", |
| 94 | + headers: { "content-type": "application/json" }, |
| 95 | + body: JSON.stringify({ |
| 96 | + host, |
| 97 | + key, |
| 98 | + keyLocation, |
| 99 | + urlList, |
| 100 | + }), |
| 101 | + }); |
| 102 | + |
| 103 | + const text = await res.text().catch(() => ""); |
| 104 | + return { status: res.status, ok: res.ok, body: text }; |
| 105 | +} |
| 106 | + |
| 107 | +// 便捷:GET ?url=https://your-site/page 也可以触发一次推送 |
| 108 | +export async function GET(req: Request) { |
| 109 | + if (REQUIRED_BEARER) { |
| 110 | + const auth = req.headers.get("authorization") || ""; |
| 111 | + if (!auth.startsWith("Bearer ") || auth.slice(7) !== REQUIRED_BEARER) { |
| 112 | + return bad("Unauthorized", 401); |
| 113 | + } |
| 114 | + } |
| 115 | + if (!INDEXNOW_KEY) return bad("Missing INDEXNOW_KEY env", 500); |
| 116 | + |
| 117 | + const { host: defaultHost } = getDefaultHostFromReq(req); |
| 118 | + if (!defaultHost) return bad("Cannot infer host from request", 500); |
| 119 | + |
| 120 | + const urlParam = new URL(req.url).searchParams.get("url") ?? undefined; |
| 121 | + const urls = dedupeValidHttps([urlParam]); |
| 122 | + if (urls.length === 0) return bad("Provide ?url=...", 400); |
| 123 | + |
| 124 | + const result = await pushToIndexNow({ |
| 125 | + host: defaultHost, |
| 126 | + key: INDEXNOW_KEY, |
| 127 | + urlList: urls, |
| 128 | + engine: "hub", |
| 129 | + }); |
| 130 | + |
| 131 | + return ok({ indexnow: result, submitted: urls }); |
| 132 | +} |
| 133 | + |
| 134 | +// 推荐:POST 更灵活,支持批量 |
| 135 | +export async function POST(req: Request) { |
| 136 | + if (REQUIRED_BEARER) { |
| 137 | + const auth = req.headers.get("authorization") || ""; |
| 138 | + if (!auth.startsWith("Bearer ") || auth.slice(7) !== REQUIRED_BEARER) { |
| 139 | + return bad("Unauthorized", 401); |
| 140 | + } |
| 141 | + } |
| 142 | + if (!INDEXNOW_KEY) return bad("Missing INDEXNOW_KEY env", 500); |
| 143 | + |
| 144 | + let body: Payload = {}; |
| 145 | + try { |
| 146 | + body = (await req.json()) as Payload; |
| 147 | + } catch { |
| 148 | + console.error("Error parsing request body"); |
| 149 | + } |
| 150 | + |
| 151 | + const { host: inferredHost } = getDefaultHostFromReq(req); |
| 152 | + const host = (body.host || inferredHost || "").replace(/^https?:\/\//, ""); |
| 153 | + if (!host) return bad("Cannot infer host; pass { host }", 400); |
| 154 | + |
| 155 | + const urls = dedupeValidHttps([ |
| 156 | + body.url, |
| 157 | + ...(body.urls || []), |
| 158 | + ...(body.urlList || []), |
| 159 | + ]); |
| 160 | + if (urls.length === 0) return bad("Provide { url } or { urls/urlList }", 400); |
| 161 | + |
| 162 | + const result = await pushToIndexNow({ |
| 163 | + host, |
| 164 | + key: INDEXNOW_KEY, |
| 165 | + urlList: urls, |
| 166 | + engine: body.engine ?? "hub", |
| 167 | + }); |
| 168 | + |
| 169 | + return ok({ indexnow: result, submitted: urls, host }); |
| 170 | +} |
0 commit comments