#Authenticate with an external server via API that generates JWT

1 messages · Page 1 of 1 (latest)

loud hearth
#

I have an external BE server build with NestJS. My colleague have set up few API endpoints that allows me to authenticate the user.

I've implemented the auth system with Redux and RTK Query but looks to me cumbersome and I would like to implement this with Server Actions since the BE server will serve me an HttpOnly Cookie and I could check if the user is logged in simply via server side.

Which is the best way to approach this refactor?

midnight zodiacBOT
#

Hi @loud hearth. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To refactor your authentication system using Server Actions in Next.js, you can follow these steps:

  1. Create a Server Action for Authentication: You can create a server action that communicates with your external BE server to authenticate the user. This server action should be treated as a public-facing API endpoint, and it should ensure that the user is authorized to perform the action. Here's an example of how you can structure your server action:
'use server'
 
import { auth } from './lib'
 
export function addItem() {
 const { user } = auth()
 if (!user) {
 throw new Error('You must be signed in to perform this action')
 }
 
 // ...
}

(Source: Next.js Docs (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#authentication-and-authorization))

  1. Handle Cookies: As per the discussion in the GitHub issue, you might face some issues with handling cookies. One user mentioned that they had to manually pass the cookies in the next request to the server. You might need to do something similar depending on how your external BE server is set up.

(Source: GitHub Issue (https://github.com/vercel/next.js/issues/60552))

  1. Server-side Validation and Error Handling: Before mutating data, you should always ensure a user is also authorized to perform the action. This can be done by checking the user's authentication status in your server action.

(Source: Next.js Docs (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#server-side-validation-and-error-handling))

#
  1. Set Cookies on Server Side: There was a discussion on GitHub about setting cookies on the server side in a server component using a server action. One of the contributors provided a demo repo which shows two ways of updating cookies from the server. You might find this useful.

(Source: GitHub Issue (https://github.com/vercel/next.js/issues/62800))

Remember, these are just guidelines and the actual implementation might vary based on your specific use case and how your external BE server is set up.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: