Edge-Flags ช่วยจัดการ feature flags สำหรับ serverless applications ได้ง่าย สร้างบน Upstash Redis พร้อม powerful geolocation rules วันนี้จะแสดงตัวอย่างง่ายๆ วิธีใช้ Edge-Flags ใน Next.js middleware rewrite requests ตาม location ของ user
สร้าง Flag
ใน example app เราอยากให้ content ใช้ได้แค่ users ใน EU เท่านั้น จึงสร้าง Redis database ใหม่ ไปที่หน้า edge-flags เลือก database ที่สร้างและ environment production
จากนั้นสร้าง flag ใหม่ชื่อ eu-countries เพิ่ม countries ทั้งหมดใน EU

Setup และติดตั้ง packages
- ถ้ายังไม่มี Next.js app สร้างด้วย
npx create-next-appติดตั้ง@upstash/edge-flagsและ@upstash/redis:
$ npm install @upstash/edge-flags @upstash/redis
- สร้างไฟล์
middleware.tsใน project root ใส่โค้ด:
// /middleware.ts
import { NextRequest, NextResponse } from "next/server";
import { Client as EdgeFlags } from "@upstash/edge-flags";
import { Redis } from "@upstash/redis";
const edgeFlags = new EdgeFlags({
redis: Redis.fromEnv()
});
export default async function middleware(
req: NextRequest,
): Promise<NextResponse> {
const enabled = await edgeFlags
.getFlag("eu-countries", req.geo ?? {})
.catch((err) => {
console.error(err);
return false;
});
if (!enabled) {
const url = new URL(req.url);
url.pathname = "/blocked";
return NextResponse.rewrite(url);
}
return NextResponse.next();
}
export const config = {
matcher: "/",
};
- สร้าง
/blockedpage แบบ sophisticated
// app/blocked/page.tsx
export default function Page() {
return <div> You are not in the EU</div>;
}
เหลือแค่ deploy โปรเจกต์ไป Vercel:
$ npx vercel
เพิ่ม environment variables ไป Vercel ไม่ว่าจะ copy จาก Upstash console หรือใช้ Upstash integration

ทดสอบ
Geolocation ใน development
Geolocation data ไม่ available ตอน develop locally ต้อง deploy จริงไป Vercel ถึงจะทดสอบได้
ตอนนี้ทดสอบได้โดยเข้า index page ของ app ถ้าอยู่ใน EU จะเห็น content มิฉะนั้น redirect ไป /blocked page