Can't get user's country code using middleware
Answered
Maine Coon posted this in #help-forum
Maine CoonOP
hey in this code below I'm trying to get the user's country code and if it matches specific countries's code restrict it from accessing specific pages, but it seems it's not working at all. I tested the code in RSC and it's working but here in the middleware it's not. can anyone help me undestand what's going on here
import { NextResponse, type NextRequest } from "next/server";
import { updateSession } from "@/utils/supabase/middleware";
import { getIp } from "./lib/get-ip";
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (pathname.startsWith("/payment") || pathname.startsWith("/register")) {
const ip = getIp();
const res = await fetch(`https://ipapi.co/${ip}/json/`);
const data = await res.json();
const country = data.country;
const restrictedCountries = ["SO", "US"];
if (restrictedCountries.includes(country)) {
return NextResponse.redirect(new URL("/restricted", request.url));
}
// Allow the request if the user is not from a restricted country
return NextResponse.next();
}
// update user's auth session
return await updateSession(request);
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};Answered by "use php"
@Maine Coon If you're deploying on vercel, it should be available in header
x-vercel-ip-country8 Replies
@Maine Coon If you're deploying on vercel, it should be available in header
x-vercel-ip-countryAnswer
@"use php" https://vercel.com/templates/next.js/edge-functions-geolocation
Maine CoonOP
yeah I'm deploying it in vercel, didn't know that, lemme check that. thank you @"use php"
@"use php" <@834006165918056458> If you're deploying on vercel, it should be available in header `x-vercel-ip-country`
Mark solution please after testing.
Thanks
Thanks
Maine CoonOP
sure, I'll do
Maine CoonOP
@"use php" hey it worked, thank you so much
how can i mark this post as Answered ?
Original message was deleted
Check out the screenshot here