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().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();
}
For now I have the code so that the user can't acess the home page if they have not logged in
Recommended threads
- Auto Updating Backend & Auth via Appwrit...
<@870607367597850624> Hey everyone 👋 I wanted to ask to ask for a friend, he’s asking if Appwrite be used in a similar way to Supabase when integrated with AI ...
- User Labels use Operator.arrayInsert(‘la...
Can I use the new db operators on user labels or roles?
- appwrite auth problem regarding the sess...
Hi, I have problem with auth. When I try to login/signup using OTP, at the end session.secret is empty, i have searched online and in the docs but i cannot find...