Use Custom Backend for Authentication in Next.js Without next-auth: A Practical Approach
Asked Answered
O

1

15

I am using Next.js 13 for development
and I have no experience with Server-Side Rendering (SSR).

what's my problem is

I have a custom backend API based on Express.js.

This backend service already implements authentication features like login, signup, logout, and even social login using Google.

I intend to continue using my existing backend authentication service instead of adopting Next.js's next-auth authentication system.
I have reasons for this decision:

  1. Next.js can be used for full-stack applications, but for me feels more like frontend side.

  2. Since my backend service is already established, I want to reuse its authentication capabilities.

currently logic In my frontend,
cookie - I'm retrieving cookies from the server fetch (next.js) to verify the user's login status.

it works fine so far (as beginner perspective)
I'm curious if there's other way to use my backend API to handle authentication similarly, without relying on next-auth.
I would like to explore alternative solutions and check if this approach is a valid strategy.

in the frontend

cookie from fetching data on the server has jwt , i decoded to put username on the navbar

Octodecimo answered 14/8, 2023 at 9:51 Comment(4)
did you get something?Alicyclic
No bro. I'm currently using NextAuth.js with the credentials provider😁Octodecimo
@Octodecimo How are you handling google/social authentication with NextAuth with your custom backend?Murat
Still facing this same issue. I'll keep tabs to see if an answer shows on how to enjoy next / next-auth and still have to use your own backend for authentication and all...not the traditional fullstack.Deathlike
T
0

i'm not sure i understand what you asked but from what i understand, yes you can,

authentication is basicly good cookies in your navigator, for example i created a website with a backend in nodejs/express js, when a user login it create a session ( in a database mine is mongobd) this session contain a UUID, this UUID is send to the client and is stored in the cookies as "session"

when i want to do something that require an authentication i simply implement the cookies in the header request and in the back i check if this cookies exist in a session if yes then i correctly does what intended to else i return a 403 code with "unauth" message and in fronted, if the response of the request is 403 then i display a message saying not authenticated, if you want to now if the client is logged in at the end of the page loading, create a simple api route that is for example called "user" and when you request this with a token but the token isn't valid it return 403 else 200

Thies answered 5/2 at 11:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.