Use NextJS middleware for proxying

This commit is contained in:
Darren Clarke 2023-05-30 09:05:40 +00:00 committed by GitHub
parent 4e4603bd71
commit df9b8abf15
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 154 additions and 94 deletions

View file

@ -1,7 +1,46 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { withAuth } from "next-auth/middleware";
import { getToken } from "next-auth/jwt";
const rewriteURL = (request: NextRequest, originBaseURL: string, destinationBaseURL: string, headers: any = {}) => {
if (request.nextUrl.pathname.includes('/_next/static/development/')) {
return NextResponse.next();
}
const destinationURL = request.url.replace(originBaseURL, destinationBaseURL);
console.log(`Rewriting ${request.url} to ${destinationURL}`);
return NextResponse.rewrite(new URL(destinationURL), { ...request.headers, ...headers });
};
const checkRewrites = async (request: NextRequest) => {
if (request.nextUrl.pathname.startsWith('/proxy/leafcutter')) {
return rewriteURL(request, process.env.LINK_URL, process.env.LEAFCUTTER_URL);
} else if (request.nextUrl.pathname.startsWith('/proxy/metamigo')) {
return rewriteURL(request, process.env.LINK_URL, process.env.METAMIGO_URL);
} else if (request.nextUrl.pathname.startsWith('/proxy/zammad')) {
const session = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET,
});
const headers = {
'X-Forwarded-User': session.email.toLowerCase(),
host: 'zammad.example.com'
};
return rewriteURL(request, `${process.env.LINK_URL}/proxy/zammad`, process.env.ZAMMAD_URL, headers);
} else if (request.nextUrl.pathname.startsWith('/assets')) {
console.log('asset');
return rewriteURL(request, `${process.env.LINK_URL}`, process.env.ZAMMAD_URL);
} else if (request.nextUrl.pathname.startsWith('/proxy/assets') || request.nextUrl.pathname.startsWith('/proxy/api')) {
console.log('proxy asset');
return rewriteURL(request, `${process.env.LINK_URL}/proxy`, process.env.ZAMMAD_URL);
}
};
export default withAuth(
() => { },
checkRewrites,
{
pages: {
signIn: `/login`,
@ -32,3 +71,4 @@ export default withAuth(
}
}
);