2

I'm using next-auth for authentication and using the Credentials provider for logging in, my API returns an object containing an accessToken like this object:

{ "token" : "UzI1NiIsInR5cCI..." },

And I'm returning a similar object containing the token in authorize property of CredentialsProviders while my session callback looks like this:

session({ session, token }) {
  session.data = {
    ...session.user,
    ...token.user,
  };
  session.accessToken = token.accessToken;
  return session;
}

And I use the useSession hook in my client code like this:

const { data: session, status } = useSession();

to access the user's token to make API requests. Is this safe? Or is there another ways to achieve this? Keep in mind that this application is gonna be fully client side rendered despite the fact that I'm using Next.js, so keep that in mind. I'm asking this because most of the docs of Next.js is SSR focused.

0

1 Answer 1

5
+25

Quite often, we use localStorage to store the token after authorization, of course, since localStorage is the browser api, this means that we store the token on the client, which is actually similar to your case. I don't see much of a security issue with this, although it does make the token vulnerable to XSS attacks, so cookies are considered a safer way to store the token, since it can't be retrieved from the script side (if you set the http-only cookie option).

If you're worried, you can put the token in cookies to be sure. Although even so, the way to use this token for malicious purposes. The best way is to protect yourself from XSS attacks and then there will be nothing to worry about, react (well, including next) out of the box has good protection mechanisms.

In general, since we are talking about an access token, this is the thing that identifies the user and this should not be a problem for you to use it into the client, you should be more careful with the secrets of the application, such as the secret that is used to encrypt the token, then there will be security problems if you give access to it by client.

If you still don't want to use a token on the client side, which you probably don't need, you can use getSession on the server side for authorized requests with nextjs and proxy your requests through next to backend, using next as api is also a common practice.

To summarize, since you are using the next-auth library, you have nothing to worry about, since it takes care of most of the security concerns. https://next-auth.js.org/getting-started/introduction#secure-by-default

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.