designly1 / nextjs14-auth-sequelize-starter

A complete starter app with Sequelze ORM and JWT authentication
27 stars 6 forks source link

401 Unauthorized calls on unprotected routes #1

Closed NINE78 closed 5 months ago

NINE78 commented 6 months ago

First of all, thanks for this excellent example on JWT authentication!

I've one question though: the AppProvider calls loadDataFromServer which targets the protected /api/auth route. Since everything is wrapped inside the AppProvider, unprotected routes like home or /login will result in 401 errors on the console (as the /api/auth route won't be accessible). Any tips on how to tackle this?

thanks!!

designly1 commented 5 months ago

Hello! Thank for bringing this to my attention. It is indeed suboptimal to make a useless request to an API endpoint when not logged in. My solution is to check for the existence of the "userData" cookie in the loadUserDataFromServer() function. So I added this function to /lib/client/auth.ts:

exportfunctionisLoggedIn() { constuserData=getUserData(); return!!userData; }

And then added this in the AppContext:

 constloadUserDataFromServer=async () => {
     if (!isLoggedIn()) return;

     try {
         constresponse=awaitfetch('/api/auth');
         constdata= (awaitresponse.json()) asI_ApiAuthResponse;
         const { success } =data;
         if (!success) {
             letmessage='Failed to load user data from server';
             if (data.message) message=data.message;
             console.error(message);
             return;
         }
         setUserDataLastLoad(newDate());
     } catch (_) {
         console.error('Failed to load user data from server');
     } finally {
         loadUserData();
     }
 };

I went ahead and pushed these changes to the repo. Thanks for your input!

Jay

------ Original Message ------ From "NINE78" @.> To "designly1/nextjs14-auth-sequelize-starter" @.> Cc "Subscribed" @.***> Date 2/8/2024 7:45:16 AM Subject [designly1/nextjs14-auth-sequelize-starter] 401 Unauthorized calls on unprotected routes (Issue #1)

First of all, thanks for this excellent example on JWT authentication!

I've one question though: the AppProvider calls loadDataFromServer which targets the protected /api/auth route. Since everything is wrapped inside the AppProvider, unprotected routes like home or /login will result in 401 errors on the console (as the /api/auth route won't be accessible). Any tips on how to tackle this?

thanks!!

— Reply to this email directly, view it on GitHub https://github.com/designly1/nextjs14-auth-sequelize-starter/issues/1, or unsubscribe https://github.com/notifications/unsubscribe-auth/ALHCNZHCVMNY2VT3NUJ5F7DYSTJGZAVCNFSM6AAAAABC7YT4JCVHI2DSMVQWIX3LMV43ASLTON2WKOZSGEZDKMRSGQ3TOMQ. You are receiving this because you are subscribed to this thread.Message ID: @.***>