#[Convex Auth] Middleware on Nextjs

11 messages · Page 1 of 1 (latest)

velvet oasis
#

Following https://labs.convex.dev/auth/authz/nextjs

After using signIn from useAuthActions by Email OTP (from resend),

const { signIn } = useAuthActions()

await signIn("resend-otp", { email , code})

on client side,

 const { isAuthenticated, isLoading } = useConvexAuth()

I see isAuthenticated = true

however,

on middleware,

import {
  convexAuthNextjsMiddleware,
  createRouteMatcher,
  isAuthenticatedNextjs,
  nextjsMiddlewareRedirect,
} from "@convex-dev/auth/nextjs/server";
 
const isSignInPage = createRouteMatcher(["/signin"]);
const isProtectedRoute = createRouteMatcher(["/product(.*)"]);
 
export default convexAuthNextjsMiddleware((request) => {
  if (isSignInPage(request) && isAuthenticatedNextjs()) {
    return nextjsMiddlewareRedirect(request, "/product");
  }
  if (isProtectedRoute(request) && !isAuthenticatedNextjs()) {
    return nextjsMiddlewareRedirect(request, "/signin");
  }
});
 
export const config = {
  // The following matcher runs middleware on all routes
  // except static assets.
  matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};

isAuthenticatedNextjs() is always false

can you guys let me know how to debug this? There is no error shown from console or terminal?

velvet oasis
#

[Convex Auth] Middleware on Nextjs

deep yoke
velvet oasis
#

Hi yes, I have ConvexAuthNextjsServerProvider at root layout

velvet oasis
#

In my convex logs, I didn't see anything, in browser network tab, what kind of requests should I check?

deep yoke
#

In my convex logs, I didn't see anything
Like actually nothing? I'd expect to at least see some requests for signIn

I guess I'd be most interested in seeing the request made when you load the link sent via email -- I believe this should be setting a cookie on localhost:3000 (or whatever dev URL you have), which is what isAuthenticatedNextjs checks for

velvet oasis
#

@deep yoke I used Email OTP, so in email sent from resend, it has only OTP code

then on web client, I call signIn with email and otp, it seems working because isAuthenticated = true

#

but when I log isAuthenticatedNextjs on middle, it said false
I tried to refresh the app, but still false, so I think cookie is not carrying over?

deep yoke
#

Ah sorry -- got Email OTP confused with magic links.

When I try with Email OTP in my demo app I have a request to localhost:3000/api/auth that sets a cookie (and then isAuthenticatedNextjs is true when I log it)

velvet oasis
#

Great I will debug and let you know

lucid mauve
#

Is it possible to get the current user on the NextJS middleware to check for a role for example?