In my current project, I am developing a Next.js application with Auth0 as the authentication system. Users are authenticated using the standard middleware:
import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge';
export default withMiddlewareAuthRequired()
However, I have encountered a challenge when it comes to storing user information in my local database. Specifically, I need to map an Auth0 userId to a local userId in order to establish relationships associated with that user. This brings me to the question of how to accomplish this effectively.
Initially, I considered handling all of this within middleware by creating something like the following snippet:
import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge';
import { NextResponse } from 'next/server';
import { getSession } from '@auth0/nextjs-auth0/edge';
import { PrismaClient } from "@prisma/client/edge";
const prisma = new PrismaClient()
export default withMiddlewareAuthRequired(async function middleware(req) {
const res = NextResponse.next();
reconcileUser(await getSession(req, res))
return res;
});
async function reconcileUser({ user }) {
const db_user = await prisma.user.upsert({
where: { auth0_uuid: user['https://auth.hydras.io/claims/uuid'] },
update: user,
create: user
})
}
Unfortunately, I discovered that utilizing Prisma within middleware is not feasible for some reason. So, the question arises - where and how should I incorporate the code to capture and maintain an updated copy of the user data in the local database?