导航菜单

Server-side API Calls in Astro

API routes

  • Place under src/pages/api/*.ts (or .js), export GET/POST handlers.
  • Return a Response object; you can use the json() helper.
  • Edge/Node runtimes depend on hosting; avoid Node-only modules if targeting Edge.
// src/pages/api/hello.ts
export async function GET() {
  return new Response(JSON.stringify({ msg: "hello" }), {
    headers: { "Content-Type": "application/json" },
  });
}

SSR pages

  • Export prerender = false in the page to enable SSR.
  • Use Astro.request for headers/query, and fetch your backend.
  • Good for user-context data, real-time, personalization; keep static when possible.

Middle-tier purposes

  • Wrap backend APIs: auth, rate-limit, signing—protect upstream.
  • Edge rendering: return personalized content close to users.
  • Progressive dynamic: list static, detail or user bits via API.

Deployment notes

  • For Cloudflare Pages Functions/Workers, stick to Fetch API; avoid Node-specific modules.
  • Configure routing so /api/* is not shadowed by static assets.
🌐
浏览器
↓ API 请求
🖥️
后端服务
↓ 转发请求
🔌
第三方 API
↑ 返回数据
🖥️
后端服务
↑ 返回数据
🌐
浏览器

Pain points of traditional FE/BE split

Calling third-party APIs in a classic split setup often hits:

  1. CORS limits: browser same-origin blocks direct calls
  2. Security: API keys may leak in frontend bundles
  3. Complexity: need a separate backend to proxy

Example with Laravel + Vue.js:

🌐
浏览器
↓ API 请求
🖥️
后端服务
↓ 转发请求
🔌
第三方 API
↑ 返回数据
🖥️
后端服务
↑ 返回数据
🌐
浏览器

Astro’s elegant solution

Astro gives a full-stack path: frontend UI + backend API together.

Now a concrete demo:

IP 信息展示

Flow

  1. Frontend component calls internal /api/ip-info
  2. Astro API route requests external IP service
  3. API route returns the result
  4. Frontend updates UI

Benefits:

  • Secrets and sensitive steps stay server-side
  • No extra backend service—simpler deploy
  • Full typing support for better DX
  • Unified error/loading handling

Advantages recap

  1. Simpler code: no separate backend API needed
  2. Developer efficiency: full-stack in one file
  3. Security: API calls server-side, keys stay hidden
  4. Performance: supports static and incremental generation

Best practices

  1. Cache smartly: build-time fetch for rarely changing data
  2. Error handling: add proper error/loading states
  3. Type safety: define response types with TypeScript
---
interface IpInfo {
  query: string;
  country: string;
  city: string;
  isp: string;
}

try {
  const response = await fetch('<http://ip-api.com/json/>');
  const ipInfo: IpInfo = await response.json();
} catch (error) {
  console.error('Failed to fetch IP info:', error);
}
---

Conclusion

With server components and API routes, Astro neatly solves API-call pain points in traditional FE/BE splits. You can ship full-stack features with concise code while keeping security and performance in check—better developer velocity, better user experience.

搜索