Last active
April 24, 2023 16:12
-
-
Save jordanmaslyn/611e755a24b255bec2462bb2d1b3d7d4 to your computer and use it in GitHub Desktop.
Proxy your Next.JS sitemaps to Yoast sitemaps using the latest middleware!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// middleware.ts | |
import { NextResponse } from "next/server"; | |
import type { NextRequest } from "next/server"; | |
// This function can be marked `async` if using `await` inside | |
export function middleware(request: NextRequest) { | |
const url = request.nextUrl; | |
url.pathname = "/api/sitemap"; | |
return NextResponse.rewrite(url); | |
} | |
export const config = { | |
matcher: [ | |
/* Match all sitemap paths */ | |
"/([\\w\\d_-]*sitemap[\\w\\d_-]*.xml)/", | |
], | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// pages/api/sitemap.ts | |
import type { NextApiRequest, NextApiResponse } from "next"; | |
export default async function handler( | |
req: NextApiRequest, | |
res: NextApiResponse | |
) { | |
const xmlRes = await fetch((process.env.NEXT_PUBLIC_WORDPRESS_URL ?? "") + req.url); | |
let xml = await xmlRes.text(); | |
res.setHeader("Content-Type", "text/xml"); | |
res.write(xml); | |
res.end(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Feel free to also reference https://gist.github.com/jordanmaslyn/7e28423ef43cdb6af068f5f192077746 for some configuration optimizations on the WordPress side.