Back

Private Route / Middleware not Working

  • 0
  • Auth
Suprised Pikachu
27 Dec, 2024, 22:51

Hello, I am trying to implement a middleware to protect the routes in my website. However it is not working as it is throwing a AppwriteException: User (role: guests) missing scope (account) at Generator.next (<anonymous>).

TL;DR
Middleware code is incorrectly checking for authentication. User isn't logged in but it throws an exception. Correct code to properly authenticate users. Solution: Update the middleware function to properly check for user authentication before returning NextResponse.next().
Suprised Pikachu
27 Dec, 2024, 22:51
TypeScript

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { Client, Account } from "appwrite";
import { appwriteConfig } from "@/lib/appwrite/config";

export async function middleware(request: NextRequest) {
  const client = new Client()
    .setProject(appwriteConfig.projectId);

  const account = new Account(client);
  let isAuthenticated; 
  isAuthenticated = await account.get();
  


  if (!isAuthenticated && request.nextUrl.pathname === "/home" ) {
    console.log(isAuthenticated);

    const signInUrl = new URL('/sign-in', request.url);
    return NextResponse.redirect(signInUrl);
  }



  return NextResponse.next();
}
Suprised Pikachu
27 Dec, 2024, 22:52

For now I have the code so that the user can't acess the home page if they have not logged in

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more