Next.js Discord

Discord Forum

Best way to handle login from external API and storing user data

Unanswered
Chinese perch posted this in #help-forum
Open in Discord
Chinese perchOP
Hi everyone. I am very new to both React and NextJS, so I am sorry if I'm not understanding things correctly here.

I have an external api (on AWS) that can handle authentication and give access to ressources. This is a serverless API, for which I pay for each request, so I would like to minimize the amount of requests made to it. This API uses JWT Tokens: a user can log in and receive his own JWT token so that he can fetch his data. But it is important that an user cannot see another user's data.

My problem is that I am unsure of how to communicate with this API in NextJS: both for authentication and storing data.

Given that my API uses JWT Tokens: What is the best way to store the JWT token in NextJS? Do I have to store it client-side (with http-only, samesite:strict and secure cookies), or is there a way to store it on the server-side securely?

I would like a way to store user-specific data on the server-side, too. Because each user has a list of contacts, projects, etc it can fetch from the API. But I don't want to request it everytime it is needed. Is there a way to cache this data on the server-side that I do not know of? Or would I have to store it client-side?

Thanks in advance!

5 Replies

Southern rough shrimp
I suggest using an auth package for nextjs with either a custom oauth implementation or social login. https://authjs.dev/
It will always be more secure than setting up cookies yourself
You can alter your external API to use the oauth spec
and then create your own provider for authjs to talk to that external api
Chinese perchOP
Thanks, I forgot to mention I toyed around with NextAuthJS already (using a CredentialProvider) but I don't know how to store the jwt given by the api afterwards.

Here is the code I used:
import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"

const handler = NextAuth({
    providers: [
        CredentialsProvider({
            name: 'Credentials',
            credentials: {
                username: { label: "Username", type: "text" },
                password: { label: "Password", type: "password" }
            },
            async authorize(credentials, req) {
                const res = await fetch("https://---.------.com/api/admins/login", {
                    method: 'POST',
                    body: JSON.stringify({ admin: { adminname: credentials.username, password: credentials.password } }),
                    headers: { "Content-Type": "application/json" }
                })
                const user = await res.json()

                if (res.ok && user) {
                    return user
                }

                return null
            }
        })
    ]
})

export { handler as GET, handler as POST }