File size: 1,256 Bytes
1e92f2d |
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 41 42 43 44 45 46 47 |
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export async function middleware(request: NextRequest) {
if (!process.env.WP_USER || !process.env.WP_APP_PASS) {
return NextResponse.next();
}
const basicAuth = `${process.env.WP_USER}:${process.env.WP_APP_PASS}`;
const pathnameWithoutTrailingSlash = request.nextUrl.pathname.replace(
/\/$/,
"",
);
const response = await fetch(
`${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/wp-json/redirection/v1/redirect/?filterBy%5Burl-match%5D=plain&filterBy%5Burl%5D=${pathnameWithoutTrailingSlash}`,
{
headers: {
Authorization: `Basic ${Buffer.from(basicAuth).toString("base64")}`,
"Content-Type": "application/json",
},
},
);
const data = await response.json();
if (data?.items?.length > 0) {
const redirect = data.items.find(
(item: any) => item.url === pathnameWithoutTrailingSlash,
);
if (!redirect) {
return NextResponse.next();
}
const newUrl = new URL(
redirect.action_data.url,
process.env.NEXT_PUBLIC_BASE_URL,
).toString();
return NextResponse.redirect(newUrl, {
status: redirect.action_code === 301 ? 308 : 307,
});
}
}
|