Menu

1 / 2

Astro Middleware: Detect Visitor Country in 15 Lines (with ApogeoAPI)

DEV Community·ApogeoAPI·7 months ago
#YVAXTSao
#astro#tutorial#edge#software#apogeoapi
Reading 0:00
15s threshold

Astro 4 ships with a middleware API that runs server-side before the page renders. Combined with ApogeoAPI, you can detect the visitor's country and pass it down to every page as a typed prop — no client-side flicker.

Setup

Astro middleware lives at src/middleware.ts . Astro automatically picks it up. Make sure your project is using output: 'server' or output: 'hybrid' in astro.config.mjs (static-only sites can't run middleware).

// astro.config.mjs import { defineConfig } from ' astro/config ' ; export default defineConfig ({ output : ' hybrid ' , adapter : /* your adapter — vercel, cloudflare, node, etc. */ , });

Enter fullscreen mode

Exit fullscreen mode

The middleware

// src/middleware.ts import { defineMiddleware } from ' astro:middleware ' ; export const onRequest = defineMiddleware ( async ( ctx , next ) => { const ip = ctx . request . headers . get ( ' x-forwarded-for ' )?. split ( ' , ' )[ 0 ] ?? ctx . request . headers . get ( ' cf-connecting-ip ' ) ?? ctx .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.