Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DarkianZ's avatar

Adding authentication system NEXTJS

HI everyone, hope you doing well.

Im struggling on making an authentication system on NextJs. Im new to this, and i usually do this in react, but as im learning next i would like to help me on this.

I've got a file useAuth.js where i write all my conditions on the authentication system. I want to know how can i implent that to the pages i want them to be auhtenticated.

Let me show you my code.


import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import axios from "../lib/axios";
import Swal from 'sweetalert2';

export const useAuth = () => {

    const router = useRouter();
    const swal = Swal();
    const [loading, setLoading] = useState(true);
    const [adminAuthenticated, setAdminAuthenticated] = useState(false);

    useEffect(() => {
        axios.get(`/api/checkAuthenticated`).then((res) => {
            if (res.status === 200) {
                setAdminAuthenticated(true);
            }
            setLoading(false);
        });
    
        return () => {
            setAdminAuthenticated(false);
        };
    }, []);

    
    axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
        if (err.response.status === 401) {
            swal("Unauthorized", err.response.data.message, "warning");
            router.push('/homepage');
        }
        return Promise.reject(err);
    });
    
    axios.interceptors.response.use(function (response) {
        return response;
    }, function (error) {
        if (error.response.status === 403)// acces denied
        {
            swal('Forbidden', error.response.data.message, "warning");
            router.push('403')
        }
        else if (error.response.status === 404)// page not found
        {
            swal('404 Error', "Url/Page Not Found", "warning");
            router.push('404')
        }
        return Promise.reject(error);
    }
    );

    if(loading)
    {
        return <h1>Loading...</h1>
    }

  
   
}

Now i want to know how to apply this conditiions on the pages, how can i call it or implement it on them.

i've tried this but i dont know if it works or if its the way to do it .


import React from "react";
import useAuth, { useAuth } from "../../hooks/useAuth";


export default function Home() {
    const useAuth = useAuth();
    return (
        <h1>This is ADMIN HOME PAGE</h1>
    )
}

Thanks guys, any information will be helpful :D

0 likes
2 replies
drehimself's avatar

I've always found Authentication with Single Page Apps to be incredibly confusing, I always try to make use of a starter package that does most of the work for me.

You didn't mention what backend you're using, I'm going to assume Laravel.

Have you seen the official Breeze/Next Starter Kit that Laravel provides?

https://laravel.com/docs/9.x/starter-kits#breeze-and-next

https://github.com/laravel/breeze-next

It assumes you're using the Breeze auth scaffolding for Laravel on the backend and Next.js on the frontend (as separate repos/projects).

On the Next.js side, it's making use of a package called "SWR" to constantly ping an endpoint to check if the user is authenticated. If not, it redirects the user back to the login page. Check out the auth.js hook to see all of the auth logic.

Now, for any pages that you want to be behind a login you can use the auth hook. Check out the AppLayout.js page, specifically const { user } = useAuth({ middleware: 'auth' }).

Give it a try locally, try running both projects and see if you can get logins working correctly.

1 like
DarkianZ's avatar

@drehimself You're rigth sir, im using laravel/nextjs in two separated folder. But on my laravel i've got a custom middleware. Following your reply, should i just do the same thing as in the github repo ?. Let's suppose i want to continue with the separated folder instead doing the breeze. How should i proceed ? This is my api on laravel

Route::post('login', [AuthController::class, 'login']);

Route::middleware(['auth:sanctum', 'isAPIAdmin'])->group(function () {

    Route::get('/checkAuthenticated', function () {
        return response()->json(['message' => 'You are in', 'status' => 200], 200);
    });

}

And this is middleware


 public function handle(Request $request, Closure $next)
    {
        if(Auth::check()){
            if(auth()->user()->type == '1')
            {
            
                return $next($request);

            }
            else
            {
                return response()->json([
                    'message'=>'Acceso denegado, no eres administrador !',
                ], 403);
            }


        }
        else
        { 
            return response()->json([
            'status'=>401,
            'message'=>'Porfavor, intente conectarse de nuevo',
            ]);
        }
    }

And my AuthController


  public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email'=>'required|max:191',
            'password'=>'required',
        ]);

        if($validator->fails())
        {
            return response()->json([
                'validation_errors'=>$validator->errors(),
            ]);
        }
        else
        {
            $user = User::where('email', $request->email)->first();

            if(! $user || ! Hash::check($request->password, $user->password))
            {
                return response()->json([
                    'status'=>401,
                    'message'=>'Datos Incorrectos',
                ]);
            }
            else
            {   
                if($user->type == 1)
                {
                    $type = "1";
                    $token = $user->createToken($user->email.'_AdminToken', ['server:admin'])->plainTextToken;

                }


                return response()->json([
                    'status'=>200,
                    'username'=>$user->name,
                    'token'=>$token,
                    'message'=>'CONECTADO',
                    'type' => $type,
                ]);
            }
        }
    }


    public function logout() {

        auth()->user()->tokens()->delete();

        return response()->json(['message' => 'DESCONECTADO'], 200);
    }

In react was so much easy for me, but i dont get it to work on nexts... it's been more than a week trying things

Please or to participate in this conversation.