This is a beta course, so its structure, chapters, and examples may continue to change.
Server-side API Calls in Astro
Astro can do API/SSR, but keep “static first, minimal runtime”. Only put what must run at runtime on the server.
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.
Traditional Frontend-Backend Separation Astro Server Component Architecture
🌐 Browser
↓ API Request
🖥️ Backend Service
↓ Forward Request
🔌 Third-party API
↑ Return Data
🖥️ Backend Service
↑ Return Data
🌐 Browser
🌐 Browser
↓ Page Request
🚀 Astro Server Component
↔️ Direct Call
🔌 Third-party API
↑ Return Complete HTML
🌐 Browser
Pain points of traditional FE/BE split
Calling third-party APIs in a classic split setup often hits:
CORS limits : browser same-origin blocks direct calls
Security : API keys may leak in frontend bundles
Complexity : need a separate backend to proxy
Example with Laravel + Vue.js:
// Laravel backend
public function getIpInfo ( Request $request) {
$response = Http :: get ( 'http://ip-api.com/json/' );
return response () -> json ($response -> json ());
} // Vue.js frontend
async function fetchIpInfo () {
const response = await fetch ( '/api/ip-info' );
const data = await response. json ();
this .ipInfo = data;
}
Traditional Frontend-Backend Separation Astro Server Component Architecture
🌐 Browser
↓ API Request
🖥️ Backend Service
↓ Forward Request
🔌 Third-party API
↑ Return Data
🖥️ Backend Service
↑ Return Data
🌐 Browser
🌐 Browser
↓ Page Request
🚀 Astro Server Component
↔️ Direct Call
🔌 Third-party API
↑ Return Complete HTML
🌐 Browser
Astro’s elegant solution
Astro gives a full-stack path: frontend UI + backend API together.
// src/pages/api/ip-info.ts
import type { APIRoute } from 'astro' ;
interface IpInfo {
query : string ;
country : string ;
city : string ;
isp : string ;
regionName : string ;
}
export const GET : APIRoute = async () => {
try {
const response = await fetch ( '<http://ip-api.com/json/>' );
if ( ! response.ok) {
return new Response (
JSON . stringify ({ error: 'Failed to fetch IP info' }),
{
status: 500 ,
headers: { 'Content-Type' : 'application/json' }
}
);
}
const data : IpInfo = await response. json ();
return new Response (
JSON . stringify (data),
{
status: 200 ,
headers: { 'Content-Type' : 'application/json' }
}
);
} catch (e) {
return new Response (
JSON . stringify ({ error: e instanceof Error ? e.message : 'Unknown error' }),
{
status: 500 ,
headers: { 'Content-Type' : 'application/json' }
}
);
}
}; ---
---
< Card surface = "base" shadow = "soft" padding = "default" data - ip - info >
< div class = "flex items-center justify-between" >
< Text as = "h3" size = "xl" weight = "semibold" > IP Info </ Text >
< Button data - refresh > Refresh </ Button >
</ div >
< Alert tone = "error" hidden data - error > </ Alert >
< Grid baseColumns = "1" columns = "2" gap = "md" hidden data - result >
< Card surface = "muted" shadow = "none" padding = "compact" >
< Text as = "div" size = "sm" tone = "muted" > IP Address </ Text >
< Text as = "div" size = "lg" data - query > </ Text >
</ Card >
</ Grid >
</ Card >
< script >
const root = document. querySelector ( '[data-ip-info]' );
const load = async () => {
const error = root?. querySelector ( '[data-error]' );
try {
const response = await fetch ( '/api/ip-info' );
if ( ! response.ok) throw new Error ( 'Failed to fetch IP info' );
const info = await response. json ();
root?. querySelector ( '[data-query]' )?. replaceChildren (info.query);
const result = root?. querySelector ( '[data-result]' );
if (result) result.hidden = false ;
} catch (cause) {
if (error) { error.textContent = cause instanceof Error ? cause.message : 'Unknown error' ; error.hidden = false ; }
}
};
root?. querySelector ( '[data-refresh]' )?. addEventListener ( 'click' , load);
load ();
</ script >
Now a concrete demo:
IP address
Country / region
Province / state
City
Internet service provider (ISP)
Flow
Frontend component calls internal /api/ip-info
Astro API route requests external IP service
API route returns the result
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
Simpler code : no separate backend API needed
Developer efficiency : full-stack in one file
Security : API calls server-side, keys stay hidden
Performance : supports static and incremental generation
Best practices
Cache smartly : build-time fetch for rarely changing data
Error handling : add proper error/loading states
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.