-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
40 lines (35 loc) · 1.54 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { GeoCookieValue } from "./types";
export async function middleware(request: NextRequest) {
// Middleware to handle the 'geo' cookie for use in homepage search
const { nextUrl: url } = request;
// path matches dynamic route
const path = /^\/([^\/]+)$/.exec(url.pathname);
// pathname is home or path (exclude files)
if (url.pathname === "/" || (path && !/\.[A-Za-z]{3}$/.test(path[1]))) {
// ip geo present with Vercel, https://vercel.com/templates/next.js/edge-functions-geolocation
if (request.ip && request.geo) {
// Getting cookies from the request using the `RequestCookies` API
const geoCookie = request.cookies.get("geo");
let geo: GeoCookieValue | undefined;
if (geoCookie) geo = JSON.parse(decodeURIComponent(geoCookie.value));
if (!geo || geo.ip !== request.ip) {
const { geo: requestGeo } = request;
const country = requestGeo.country || "pt-BR"; // for use somewhere
const lat = Number(requestGeo.latitude);
const lng = Number(requestGeo.longitude);
const newCookie: GeoCookieValue = { country, lat, lng, ip: request.ip };
// Setting cookies on the response using the `ResponseCookies` API
const response = NextResponse.next();
response.cookies.set({
name: "geo",
value: encodeURIComponent(JSON.stringify(newCookie)),
path: "/",
httpOnly: true,
});
return response;
}
}
}
}