samratarmas
CDCloudflare Developers
•Created by samratarmas on 6/29/2023 in #pages-help
Can Pages Function Middleware change incoming request?
Hello team, nice community here! This is my first question in the discord and its very simple:
Can you rewrite (not redirect) the destination URL from inside a function middleware in pages?
The docs on middleware shows how you can intercept request destination handler and call some other tasks before it, or after it, but I would like to take that incoming request and rewrite it to a
[slug]
directory similar to the following NestJS middleware setup:
Code snippet for nextjs middleware:
import { NextRequest, NextResponse } from "next/server";
export default async function middleware(req: NextRequest) {
const url = req.nextUrl;
// Get hostname of request (e.g. demo.vercel.pub, demo.localhost:3000)
const hostname = req.headers
.get("host")!
.replace(".localhost:3000", .${process.env.NEXT_PUBLIC_ROOT_DOMAIN});
// Get the pathname of the request (e.g. /, /about, /blog/first-post)
const path = url.pathname;
// Rewrite to /[domain]/[path] dynamic route
return NextResponse.rewrite(new URL(/${hostname}${path}, req.url));
}
Snippet end
In summary, if the [slug]
is acme
then I want to rewrite acme.myapp.com
to route to nextjs app/[acme]/layout.ts
corresponding static assets from next build
, given that acme
subdomain is mapped with Cloudflare for Saas.
I was hoping to use static export of nextJS (no SSR, so it opts out of nextJS middleware altogether), along with Cloudflare Pages Functions to regain the opted out functionality, and seems like pages also has the primitives using _middleware.js
If any team member caught eye on this it would mean a lot if you can get attention of someone that is more expereinced with this regard., maybe @Walshy | Pages or the team that is working with the next-on-pages library, Looking forward!35 replies