Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Redis

Implement Edge Flags ใน Next.js Middleware สำหรับ Geo-Based Content Control

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

Implement Edge Flags ใน Next.js Middleware สำหรับ Geo-Based Content Control

Setup และติดตั้ง packages

  1. ถ้ายังไม่มี Next.js app สร้างด้วย npx create-next-app ติดตั้ง @upstash/edge-flags และ @upstash/redis:
$ npm install @upstash/edge-flags @upstash/redis
  1. สร้างไฟล์ 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: "/",
};
  1. สร้าง /blocked page แบบ 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

Implement Edge Flags ใน Next.js Middleware สำหรับ Geo-Based Content Control

ทดสอบ

Geolocation ใน development

Geolocation data ไม่ available ตอน develop locally ต้อง deploy จริงไป Vercel ถึงจะทดสอบได้

ตอนนี้ทดสอบได้โดยเข้า index page ของ app ถ้าอยู่ใน EU จะเห็น content มิฉะนั้น redirect ไป /blocked page

Links