Add middleware for onboarding page

This commit is contained in:
Meier Lukas
2023-08-05 12:26:50 +02:00
parent 2615f8e0ae
commit f18d2fdfbd
3 changed files with 53 additions and 0 deletions

47
src/middleware.ts Normal file
View File

@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from 'next/server';
import { env } from 'process';
import { client } from './utils/api';
const skippedUrls = [
'/onboard',
'/api/',
'/_next/',
'/favicon.ico',
'/404',
'/pages/_app',
'/imgs/',
];
let cachedUserCount = 0;
export async function middleware(req: NextRequest) {
const url = req.nextUrl.clone();
// Do not redirect if the url is in the skippedUrls array
if (skippedUrls.some((skippedUrl) => url.pathname.startsWith(skippedUrl))) {
return NextResponse.next();
}
// Do not redirect if we are on Vercel
if (env.VERCEL) {
return NextResponse.next();
}
// Do not redirect if there are users in the database
if (cachedUserCount > 0) {
return NextResponse.next();
}
// is only called from when there were no users in the database in this session (Since the app started)
cachedUserCount = await client.user.count.query();
// Do not redirect if there are users in the database
if (cachedUserCount > 0) {
return NextResponse.next();
}
url.pathname = '/onboard';
return NextResponse.redirect(url);
}

View File

@@ -30,6 +30,10 @@ export const userRouter = createTRPCRouter({
isAdmin: true, isAdmin: true,
}); });
}), }),
count: publicProcedure.query(async ({ ctx }) => {
const count = await ctx.prisma.user.count();
return count;
}),
createFromInvite: publicProcedure createFromInvite: publicProcedure
.input( .input(
signUpFormSchema.and( signUpFormSchema.and(

View File

@@ -54,6 +54,8 @@ export const api = createTRPCNext<RootRouter>({
ssr: false, ssr: false,
}); });
export const client = createTRPCProxyClient<RootRouter>(getTrpcConfiguration());
/** /**
* Inference helper for inputs. * Inference helper for inputs.
* *