Skip to content

Instantly share code, notes, and snippets.

@jordanmaslyn
Last active April 24, 2023 16:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanmaslyn/611e755a24b255bec2462bb2d1b3d7d4 to your computer and use it in GitHub Desktop.
Save jordanmaslyn/611e755a24b255bec2462bb2d1b3d7d4 to your computer and use it in GitHub Desktop.
Proxy your Next.JS sitemaps to Yoast sitemaps using the latest middleware!
// 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)/",
],
};
// 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();
}
@jordanmaslyn
Copy link
Author

Feel free to also reference https://gist.github.com/jordanmaslyn/7e28423ef43cdb6af068f5f192077746 for some configuration optimizations on the WordPress side.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment