bash Copy code
# Step 1: Create a new SvelteKit project
npx sv create@latest low-latency-app
cd low-latency-app
# Step 2: Install the Vercel adapter for Edge Functions
npm install @sveltejs/adapter-vercel
# Step 3: Replace the contents of the key files as shown below
# Then run `npm run dev` to test locally (APIs will be Node.js runtime locally, Edge only on deploy)
# Step 4: Deploy to Vercel for Edge runtime
npm install -g vercel
vercel --prod
Project Overview
This is a minimal SvelteKit app demonstrating ultra-low latency APIs using Vercel Edge Functions .
Frontend : A home page with a button to fetch your IP geolocation (country, city) and measure round-trip latency.
API : /api/geo endpoint runs in Vercel Edge Runtime (global CDN, no cold starts, <10ms latency typically).
Why low latency? Edge Functions execute closest to the user. The API reads geolocation from Vercel's built-in headers (x-vercel-ip-country, etc.) – no external calls!
Local dev : APIs run in Node.js (higher latency). Deploy to Vercel to see Edge magic.
Demo : After deploy, open in incognito – latency often <50ms worldwide!
File Structure (Key Files Only)
code Copy code
low-latency-app/
├── package.json # (auto-generated, add "vercel": "vercel --prod" script if desired)
├── svelte.config.js
├── src/
│ ├── app.html
│ ├── routes/
│ │ ├── +layout.svelte
│ │ └── +page.svelte
│ └── routes/api/geo/
│ └── +server.js
└── vite.config.js # (default, no changes needed)
File Contents
svelte.config.js
js Copy code
import adapter from '@sveltejs/adapter-vercel';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter({
// Enable Edge Runtime for all +server.js routes by default
runtime: 'edge'
})
}
};
export default config;
src/app.html
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover" class="bg-gradient-to-br from-blue-500 to-purple-600 min-h-screen flex items-center justify-center p-4">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
src/routes/+layout.svelte
svelte Copy code
<script>
// Global layout – optional loading spinner or theme
</script>
<slot />
<style>
/* Gradient background already in app.html */
</style>
src/routes/+page.svelte
svelte Copy code
<script>
import { onMount } from 'svelte';
let ip = '';
let country = '';
let city = '';
let latency = '';
let loading = false;
let error = '';
async function fetchGeo() {
loading = true;
error = '';
const start = performance.now();
try {
const response = await fetch('/api/geo');
const data = await response.json();
const end = performance.now();
ip = data.ip;
country = data.country;
city = data.city;
latency = `${Math.round(end - start)} ms`;
} catch (err) {
error = 'Failed to fetch (check console)';
console.error(err);
} finally {
loading = false;
}
}
onMount(() => {
// Auto-fetch on load for demo
fetchGeo();
});
</script>
<main class="max-w-md mx-auto bg-white/80 backdrop-blur-xl rounded-2xl p-8 shadow-2xl border border-white/50">
<h1 class="text-3xl font-bold text-center text-gray-800 mb-8">
🚀 Edge Latency Demo
</h1>
<p class="text-center text-gray-600 mb-6 text-lg">
Powered by <strong>SvelteKit + Vercel Edge Functions</strong><br>
APIs run globally at the edge for ultra-low latency!
</p>
<button
on:click={fetchGeo}
disabled={loading}
class="w-full bg-gradient-to-r from-blue-500 to-purple-600 text-white py-4 px-6 rounded-xl font-semibold text-lg shadow-lg hover:shadow-xl transform hover:-translate-y-1 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed mb-8"
>
{#if loading}
🔄 Fetching...
{:else}
📍 Get My Location & Latency
{/if}
</button>
{#if error}
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-xl mb-4">
{error}
</div>
{/if}
{#if ip}
<div class="space-y-4">
<div class="bg-gradient-to-r from-green-400 to-blue-500 text-white p-6 rounded-xl shadow-lg">
<h2 class="font-bold text-xl mb-2">📊 Results</h2>
<p><strong>Latency:</strong> {latency} ⚡</p>
<p><strong>IP:</strong> {ip}</p>
<p><strong>Country:</strong> {country}</p>
<p><strong>City:</strong> {city}</p>
</div>
<p class="text-sm text-gray-500 text-center italic">
* Latency is round-trip client-to-edge. Try from different locations!
</p>
</div>
{/if}
</main>
src/routes/api/geo/+server.js
js Copy code
import { json } from '@sveltejs/kit';
/** @type {import('./$types').RequestHandler} */
export async function GET({ request }) {
// Edge Runtime config (Vercel auto-detects)
// No cold starts, runs on global CDN closest to user
const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ?? 'unknown';
const country = request.headers.get('x-vercel-ip-country') ?? 'unknown';
const city = request.headers.get('x-vercel-ip-city') ?? 'unknown';
const region = request.headers.get('x-vercel-ip-region') ?? 'unknown';
// Ultra-fast response: pure headers, no DB/external calls
return json({
ip,
country,
city,
region,
timestamp: Date.now(),
message: 'Served from Vercel Edge! 🌍'
});
}
// Explicit Edge config (optional, adapter handles it)
export const config = {
runtime: 'edge'
};
Run & Deploy
Local dev : npm run dev → Open http://localhost:5173 . Latency ~10-50ms (local Node.js).
Deploy : vercel --prod (login if prompted). Gets a *.vercel.app URL.
Test latency : Open deployed URL from phone/VPN/different country. See <20ms often!
Scale : Add more APIs (e.g., /api/ping, /api/counter). All +server.js auto-Edge.
Custom domain : vercel --prod → Add domain in Vercel dashboard.
Why This Rocks for Production
Latency : Edge > Lambda/Node (no cold starts, geo-routing).
SvelteKit perks : File-based routing, SSR, zero-config deploy.
Extend : Add auth (headers), DB (PlanetScale/Turso edge), AI (run models at edge).
Costs : Vercel Hobby = free for this.
Ping me for enhancements like real-time WebSockets or auth! 🕵️♂️