#NextJs Account Realtime connection with no trace
1 messages · Page 1 of 1 (latest)
How are you authenticating in your app? SSR?
right here in the second useEffect i check for a session if there is one i set a cookie with the userId and i have a middleware that is checking if there is any cookie and if it is then its "authenticated" and on the frontend i js call the account.get
useUser hook:
export const UserProvider: React.FC... => {
const [user, setUser] ...
const client = Connection();
const account = new Account(client);
useEffect(() => {
console.log('useEffect');
const _subscribe =client.subscribe('account', response => {
console.log(response);
setUser(null);
});
return () => {
_subscribe();
}
}, []);
useEffect(() => {
async function getUser() {
const user = await account.get();
if (user) {
const {name, email, prefs, labels} = user;
setUser({id: user['$id'], name, email, prefs, labels});
const currentSession = await account.getSession('current');
document.cookie = `a=${currentSession}; path=/; max-age=31536000;`;
toast.success('Sikeres bejelentkezés!');
}
return
}
getUser();
}, []);
retrun ...
middleware:
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { adminClient, createSessionClient } from "./lib/appwiteAdmin";
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const cookies = request.cookies;
const { account } = await createSessionClient();
if(cookies.get("a") && account) {
if (pathname === "/auth/login" || pathname === "/") {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
return NextResponse.next();
} else {
if (pathname !== "/auth/login") {
return NextResponse.redirect(new URL("/auth/login", request.url));
}
return NextResponse.next();
}
}
export const config = {
matcher: "/((?!_next|favicon.ico|asfap_bg.png|asfap_rounded.png).*)",
};
on the front end i js read from the user obj with the useUser hook or use the account.get
I couldnt resolve to do an SSR authentication cuz of some errors that i understand now but for now this is how it works
UPDATE: now on the page initial load the cookie value is set to be the session id and on the backend i used this for authentication: ```javascript
export async function createSessionClient() {
const client = new Client()
.setEndpoint(endPoint)
.setProject(projectId);
const session = (await cookies()).get("a");
if (!session || !session.value) {
throw new Error("No session");
}
client.setSession(session.value);
return {
get account() {
return new Account(client);
},
};
}
wich is now called on the middleware and check if there is an accoun on this session like in the docs. But still no message on the realtime ws and its still not working.
You need a client side session created, this has to be made with the "appwrite" package. You'd need to fetch your cookie from the server side and set it in the client for realtime to auth and work