idempotentI
Convex Community2y ago
6 replies
idempotent

How can I use Convex in the Next.js middleware?

I am trying to use Convex in my middleware like so, but
ctx.auth.getUserIdentity()
in my action keeps returning
null
, I believe that this is due it running on the server so it is not wrapped with <ConvexProviderWithClerk />:
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';
import { fetchAction } from 'convex/nextjs';
import { NextResponse } from 'next/server';

import { api } from '@/convex/_generated/api';
import { env } from '@/env';

const isPrivateRoute = createRouteMatcher([`${env.NEXT_PUBLIC_AFTER_AUTH_REDIRECT_URL}(.*)`]);
const isAuthRoute = createRouteMatcher([
  `${env.NEXT_PUBLIC_CLERK_SIGN_IN_URL}(.*)`,
  `${env.NEXT_PUBLIC_CLERK_SIGN_UP_URL}(.*)`,
]);

export default clerkMiddleware(async (auth, req) => {
  const { url } = req;
  const user = await fetchAction(api.clerk.user.getUserInfo);
  console.log(user.user.stripeUserId);

  if (isAuthRoute(req)) {
    return NextResponse.redirect(new URL(env.NEXT_PUBLIC_AFTER_AUTH_REDIRECT_URL, url));
  } else if (isPrivateRoute(req)) {
    auth().protect();
    return auth().redirectToSignIn();
  }

  return NextResponse.next();
});

export const config = {
  matcher: [
    '/((?!.*\\..*|_next).*)', // Don't run middleware on static files
    '/', // Run middleware on index page
    '/(api|trpc)(.*)', // Run middleware on API routes
  ],
};
Was this page helpful?