diff --git a/src/middleware.ts b/src/middleware.ts new file mode 100644 index 000000000..fffd32324 --- /dev/null +++ b/src/middleware.ts @@ -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); +} diff --git a/src/server/api/routers/user.ts b/src/server/api/routers/user.ts index ded156486..ad04942c4 100644 --- a/src/server/api/routers/user.ts +++ b/src/server/api/routers/user.ts @@ -30,6 +30,10 @@ export const userRouter = createTRPCRouter({ isAdmin: true, }); }), + count: publicProcedure.query(async ({ ctx }) => { + const count = await ctx.prisma.user.count(); + return count; + }), createFromInvite: publicProcedure .input( signUpFormSchema.and( diff --git a/src/utils/api.ts b/src/utils/api.ts index 241c0af95..16c69e181 100644 --- a/src/utils/api.ts +++ b/src/utils/api.ts @@ -54,6 +54,8 @@ export const api = createTRPCNext({ ssr: false, }); +export const client = createTRPCProxyClient(getTrpcConfiguration()); + /** * Inference helper for inputs. *