Menu

Post image 1
Post image 2
1 / 2
0

SvelteKit Localized Pricing with ApogeoAPI in 30 Lines (Server Hooks)

DEV Community·ApogeoAPI·29 days ago
#IprCXGHg
Reading 0:00
15s threshold

SvelteKit's server hooks run on every request before the page is rendered. Combined with ApogeoAPI, you can detect the visitor's country and look up the live exchange rate, then pass everything down to every +page.svelte as typed locals. The hook // src/hooks.server.ts import type { Handle } from ' @sveltejs/kit ' ; import { APOGEOAPI_KEY } from ' $env/static/private ' ; const APOGEO = ' https://api.apogeoapi.com/v1/api/geo ' ; export const handle : Handle = async ({ event , resolve }) => { const ip = event . request . headers . get ( ' x-forwarded-for ' )?. split ( ' , ' )[ 0 ] ?? event . getClientAddress (); if ( ip && APOGEOAPI_KEY ) { try { const res = await fetch ( ` ${ APOGEO } /ip/ ${ ip } ` , { headers : { ' X-API-Key ' : APOGEOAPI_KEY }, }); if ( res . ok ) { const data = await res . json (); event . locals . geo = { country : data . country ?. iso2 , currency : data . country ?. currency , rate : data . country ?.…

Continue reading — create a free account

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

Read More