Using Auth0 and Prisma to capture user information

27 Views Asked by At

I'm building a Next.js app using Auth0 as the authentication system. Users are logged in using the standard middleware:

import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge';

export default withMiddlewareAuthRequired() 

However, I'd like to maintain some information about the user in my local database (for instance, mapping an auth0 userId to a local userId in order to attach relationships to that user). My question however, surrounds how to do this.

Initially, I did think I could do this all in middleware, something along the lines of:

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
  })
}

but it seems that you can't use Prisma in middleware for whatever reason. Therefore, where/how can I put the code to capture the user like this and ensure we have an up-to-date copy within the database locally?

1

There are 1 best solutions below

1
Neer Amrutia On

If you are using next-auth , you can visit the official docs which will clear all your doubts : https://next-auth.js.org/configuration/initialization

You can get the code here which I used to authenticate users using next-auth : https://github.com/neeramrutia/nextjs_project_manager/tree/main/app/api/auth/%5B...nextauth%5D

Note : There is a specific file/folder structure you need to follow