-4

I need want to send the only authenticated user to the /chat route in next js how to do ut using the middleware? Although I created a middleware and place it inside the root folder it dosen't detect the api call any one who use /chat can go to the chat page?[folder structure]enter image description here

// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  const token = request.cookies.get('token')?.value;
  console.log("hi there from middleware");
console.log('Middleware - Token:', token  );

  // if user is not logged in and visiting /chat
  if (!token && request.nextUrl.pathname.startsWith('/chat')) {
    return NextResponse.redirect(new URL('/login', request.url))
  }

  return NextResponse.next()
}

export const config = {
  matcher: ['/chat/:path*'],
}

1 Answer 1

3

The authentication logic while creating the user, seems to be a problem in here, I have implemented the same authentication flow using Supabase auth. In supabase they have their own middleware request which they pass it to the root middleware, which then processes everything.

This is their create user snippet( From their docs)

const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return request.cookies.getAll();
        },
        setAll(cookiesToSet) {
          cookiesToSet.forEach(({ name, value }) =>
            request.cookies.set(name, value)
          );
          supabaseResponse = NextResponse.next({
            request,
          });
          cookiesToSet.forEach(({ name, value, options }) =>
            supabaseResponse.cookies.set(name, value, options)
          );
        },
      },
    }
  );

Consider changing your create user logic flow, other things seems to be ok, your check for non authenticated user is fine.

Sign up to request clarification or add additional context in comments.

2 Comments

so I need to integrate the supbase to nextjs front end side right?
Yes, that would be easy and quick in your case. I have implemented this whole auth flow from their docs in two of my projects. It works fine. The user will not be redirected to chat, until they are authenticated. supabase.com/docs/guides/auth/server-side/nextjs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.