#Help with refresh tokens

3 messages · Page 1 of 1 (latest)

scenic bramble
#

Hello, there is a problem with the fact that /api/auth/session from next-auth is called twice in a row when the page loads

GET /api/auth/session 200 in 20 ms
GET /api/auth/session 200 in 14 ms

Because of this, the refresh Access Token behaves incorrectly and when I resend it, I get an error that this token has already been reset. How do I remove the repeated call to /api/auth/session when loading a page? The code used is shown below.
"next": "14.2.2",
"next-auth": "^4.24.7",

Thanks!

boreal irisBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

scenic bramble
#
async function refreshAccessToken(token: any) {
    try {
        const data = {
            staffId: token.staffId,
            refreshToken: token.refreshToken
        }
        const res = await axios.post('/api/v1/admin/staff/refresh_token', data);
        const refreshedTokens = await res.data;
        token.accessToken = refreshedTokens.result.accessToken
        token.accessTokenExpires = Date.now() + 900 * 1000
        token.refreshToken = refreshedTokens.result.refreshtoken
        console.log(token)
        return token
    } catch (e) {
        console.log("Error")
        console.log(e)

        return {
            error: "RefreshAccessTokenError",
        }
    }
}

export const authOptions: any = {
    providers: [
        CredentialsProvider({
            id: 'credentials',
            name: "Credentials",
            credentials: {
                email: { label: "Name", type: "text" },
                password: { label: "Password", type: "password" },
            },

            async authorize(credentials: any) {
                try {
                    ...
                } catch (error: any) {
                    throw new Error(error);
                }
            }
        })
    ],
    callbacks: {
        async jwt({ token, user, account, profile, isNewUser }: any) {
            if (user) {
                token.accessToken = user.result.accessToken
                token.accessTokenExpires = Date.now() + 900 * 1000
                token.refreshToken = user.result.refreshToken
                token.staffId = user.staffId
            }

            if (Date.now() < token.accessTokenExpires) {
                return token
            }
            return refreshAccessToken(token)
        },
    }
}