diff --git a/lib/validations/url.ts b/lib/validations/url.ts index 0169f4f..c941828 100644 --- a/lib/validations/url.ts +++ b/lib/validations/url.ts @@ -14,7 +14,7 @@ import * as z from "zod"; */ const urlPattern = /^(?!-)[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*(? { // console.log(req.auth); - const ip = req.headers.get("X-Forwarded-For"); - - if (req.url.includes("/s/")) { - const match = req.url.match(/[^/]+$/); - let geo = { - city: "", - region: "", - country: "", - latitude: "", - longitude: "", - }; - const data = await fetch(`https://ip.wr.do/api?ip=${ip}`); // http://ip-api.com/json/42.48.83.141 - if (data.ok) { - const geoData = await data.json(); - geo = { - city: geoData.city, - region: geoData.region, - country: geoData.country, - latitude: geoData.latitude, - longitude: geoData.longitude, + try { + const ip = req.headers.get("X-Forwarded-For"); + if (req.url.includes("/s/")) { + const match = req.url.match(/[^/]+$/); + let geo = { + city: "", + region: "", + country: "", + latitude: "", + longitude: "", }; - } - - if (match) { - const res = await fetch( - `${siteConfig.url}/api/s?slug=${match[0]}&ip=${ip}&city=${geo.city}®ion=${geo.region}&country=${geo.country}&latitude=${geo.latitude}&longitude=${geo.longitude}`, - { - method: "GET", - }, - ); - - if (!res.ok) { - return NextResponse.redirect(`${siteConfig.url}/docs/short-urls`); + const data = await fetch(`https://ip.wr.do/api?ip=${ip}`); // http://ip-api.com/json/42.48.83.141 + if (data.ok) { + const geoData = await data.json(); + geo = { + city: geoData.city, + region: geoData.region, + country: geoData.country, + latitude: geoData.latitude, + longitude: geoData.longitude, + }; } - const target = await res.json(); - if (!target) { - return NextResponse.redirect(`${siteConfig.url}/docs/short-urls`); + if (match) { + const res = await fetch( + `${siteConfig.url}/api/s?slug=${match[0]}&ip=${ip}&city=${geo.city}®ion=${geo.region}&country=${geo.country}&latitude=${geo.latitude}&longitude=${geo.longitude}`, + { + method: "GET", + }, + ); + + if (!res.ok) { + return NextResponse.redirect(`${siteConfig.url}/docs/short-urls`); + } + + const target = await res.json(); + if (!target) { + return NextResponse.redirect(`${siteConfig.url}/docs/short-urls`); + } + return NextResponse.redirect(target); } - return NextResponse.redirect(target); } + + return NextResponse.next(); + } catch (error) { + return NextResponse.redirect(`/`); } - - return NextResponse.next(); }); // Read more: https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher