Next.js Discord

Discord Forum

How to know if user is auth or not

Answered
Yuss posted this in #help-forum
Open in Discord
I'm trying to customise my navbar if user is log or not and i have a middleware who check route, if token doesn't exist into cookie i redirect it into login page but i don't who to implement verification if log or not
Answered by Yuss
a issue i didn't set coookie for js-cookie into front i had just back cookie
View full answer

23 Replies

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { authRoutes, protectedRoutes } from './router/router';

export function middleware(request: NextRequest) {
    const token = request.cookies.get('token')?.value;
    const userId = request.cookies.get('userId')?.value;

    if (
        protectedRoutes.includes(request.nextUrl.pathname) &&
        (!token || token === 'undefined') && (!userId || userId === 'undefined')
    ) {
        request.cookies.delete('token');
        const response = NextResponse.redirect(new URL('/login', request.url));
        response.cookies.delete('token');
        return response;
    }

    // Si la route est une route d'authentification, rediriger l'utilisateur connecté vers une page du tableau de bord
    if (authRoutes.includes(request.nextUrl.pathname) && token && token !== 'undefined' && userId && userId !== 'undefined') {
        const response = NextResponse.redirect(new URL('/dashboard', request.url));
        return response;
    }

    // Si la route n'est ni protégée ni une route d'authentification, continuer le flux normal
    return NextResponse.next();
}
It's my middleware
you could use cookies() function on page component and do what you did in middleware
create a route handler and a custom hook if you need it on client side
mhhh
do you an example of code pls ?
@Yuss
Have you looked at
https://next-auth.js.org/
wait is not const { auth } = currentuser ()
i thnik i don't need nextauth, my signin works i just need to verify if log or not
that's my api/login


 if (req.method === 'GET') {
        const token = req.cookies.token;
        const userId = req.cookies.userId;


        console.log('token', token);

        if (token && token !== 'undefined' && userId && userId !== 'undefined') {
            res.status(200).json({ message: 'user already log' });
            return;
        } else {
            res.status(200).json({ message: 'user not log' });
            return;
        }
    }


to get if user log or not


and i try to implement this here :
into root layout
export default function RootLayout({
    children,
}: {
    children: React.ReactNode;
}) {


    fetch("http://localhost:3000/api/login", {
        method: "GET",
        headers: {
            "Content-Type": "application/json",
        },
        credentials: "include",
    })
        .then((res) => res.json())
        .then((data) => {
            console.log(data);
        });

    return (
        <html lang="en" suppressHydrationWarning className="h-full">
            <head />
            <body className="bg-[#EEF5FF] font-sans antialiased mb-4 min-h-screen">
                <NavBar />
                <Providers themeProps={{ attribute: "class", defaultTheme: "light" }}>
                    <div className="relative flex flex-col min-h-screen">
                        <main className="container max-w-full pt-10 px-6 flex-grow">
                            {children}
                        </main>
                    </div>
                </Providers>
            </body>
        </html>
    );
}
but he say token undefined but i have my token into my cookies
and i saw some people do use getServerProps but i don't know how this functions works
Polish
something like this might work. if you can validate the session
let isAuth = await verifySession()
return <>{isAuth ? <AuthNavBar /> : <OtherNavBar />}</>
mhh okay i'm gona check this thkx
@Yuss mhh okay i'm gona check this thkx
Polish
did it work?
sorry, i didn't saw your message
i made some research
a issue i didn't set coookie for js-cookie into front i had just back cookie
Answer
so now it works
thkx for your help