Back

Middleware for NextJS

  • 0
  • Web
  • Cloud
BakaPresident
28 Aug, 2024, 15:08

Hi guys, can i check if i'm planning to use middleware.ts i'm supposed to use node-appwrite right? I'm using just the appwrite one and it doesn't seem to work.

Keeps saying i'm not authenticated while i already am

TL;DR
Developers are experiencing authentication issues when using middleware in NextJS with the 'appwrite' library instead of 'node-appwrite'. It is recommended to use 'node-appwrite' for authentication in middleware.ts.
BakaPresident
28 Aug, 2024, 15:38

In addition i've tried

TypeScript
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { appwriteServerAccount } from './lib/server/appwriteServer'


export async function middleware(request: NextRequest) {
    if (request.nextUrl.pathname.startsWith('/dashboard')) {
        const user = await appwriteServerAccount.get();
        console.log(user)

        if (!user) {
            return NextResponse.redirect(new URL('/login', request.url))
        }
    }

    return NextResponse.next()
}

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

and

TypeScript
import { Account } from 'node-appwrite';
import { Client } from 'node-appwrite';

const appwriteServerClient = new Client();

appwriteServerClient
    .setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT as string)
    .setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID as string)
    .setKey(process.env.APPWRITE_SECRET_API_KEY as string);


export const appwriteServerAccount = new Account(appwriteServerClient);
export default appwriteServerClient;

But it still says i'm not authenticated

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