55 lines
1.9 KiB
TypeScript
55 lines
1.9 KiB
TypeScript
import {
|
|
convexAuthNextjsMiddleware,
|
|
createRouteMatcher,
|
|
isAuthenticatedNextjs,
|
|
nextjsMiddlewareRedirect,
|
|
} from "@convex-dev/auth/nextjs/server";
|
|
import { NextResponse } from "next/server";
|
|
|
|
const isSignInPage = createRouteMatcher(["/auth"]);
|
|
const isProtectedPage = createRouteMatcher([
|
|
"/app(.*)",
|
|
"/onboarding(.*)",
|
|
]);
|
|
|
|
export default convexAuthNextjsMiddleware(async (request) => {
|
|
const { pathname, search } = request.nextUrl;
|
|
if (pathname === "/app" || pathname === "/app/") {
|
|
return NextResponse.redirect(new URL(`/app/dashboard${search || ""}`, request.url));
|
|
}
|
|
const legacyRedirects: Record<string, string> = {
|
|
"/dashboard": "/app/dashboard",
|
|
"/search": "/app/search",
|
|
"/inbox": "/app/inbox",
|
|
"/settings": "/app/settings",
|
|
"/data-sources": "/app/data-sources",
|
|
"/help": "/app/help",
|
|
"/leads": "/app/inbox",
|
|
"/opportunities": "/app/search",
|
|
};
|
|
const legacyMatch = Object.keys(legacyRedirects).find((path) =>
|
|
pathname === path || pathname.startsWith(`${path}/`)
|
|
);
|
|
if (legacyMatch) {
|
|
const targetBase = legacyRedirects[legacyMatch];
|
|
const suffix = pathname.slice(legacyMatch.length);
|
|
const target = `${targetBase}${suffix}${search || ""}`;
|
|
return NextResponse.redirect(new URL(target, request.url));
|
|
}
|
|
|
|
if (isSignInPage(request) && (await isAuthenticatedNextjs())) {
|
|
return nextjsMiddlewareRedirect(request, "/app/dashboard");
|
|
}
|
|
if (isProtectedPage(request) && !(await isAuthenticatedNextjs())) {
|
|
const nextUrl = new URL("/auth", request.url);
|
|
nextUrl.searchParams.set("next", request.nextUrl.pathname + request.nextUrl.search);
|
|
return NextResponse.redirect(nextUrl);
|
|
}
|
|
});
|
|
|
|
export const config = {
|
|
// The following matcher runs middleware on all routes
|
|
// except static assets.
|
|
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
|
|
};
|