Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

254
Visualizações
Where to store JWT token from an API in next-auth

I implemented this in next-auth following some tutorial online

import NextAuth from "next-auth"
import Providers from "next-auth/providers";
const https = require('https');

export default NextAuth({
  providers: [
    Providers.Credentials({
      name: 'Credentials',
      credentials: {
        email: { label: "Email", type: "email" },
        password: {  label: "Password", type: "password" }
      },
      async authorize(credentials) {
        const url = 'https://localhost/auth';

        const httpsAgent = new https.Agent({
          rejectUnauthorized: false,
        });

        const res = await fetch(url, {
          method: 'POST',
          body: JSON.stringify(credentials),
          agent: httpsAgent,
          headers: {
            "Content-Type": "application/json"
          }
        })
        const user = await res.json();

        if (res.ok && user) {
          return user;
        } else {
          return null;
        }
      }
    }),
    // ...add more providers here
  ],
  callbacks: {
    async jwt(token, user, account, profile, isNewUser) {
      if (user?.type) {
        token.status = user.type
      }
      if (user?.username) {
        token.username = user.username;
      }

      return token
    },

    async session(session, token) {
      session.type = token.type;
      session.username = token.username;
      return session
    }
  }
})

pretty standard. https://localhost/auth return an object like this (I called it user for now)

{
  token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE2MzY0MTE4NjEsImV4cCI6MTYzNjQxNTQ2MSwicm9sZXMiOlsiUk9MRV9VU0VSIl0sInVzZXJuYW1lIjoiZXJuYTM5QHdlYmVyLmNvbSJ9.Abenx1GhB-_d9LVpLfa2NYp62Lbw6U65EUQowA0jA_aykx1m-BlBR_YBcL4XIJsknJ99NN8Ees4Zxdsphfhjs7du4TR2MgTITHYy-BYjBX9CsluVSBpm-L7c-oK5vu70eumAy1ixy5MKOTN2EQYCm65RszSheIwZ4LN8vSuzxzZuLszRG9nbpauiHDpYCeLrNeNkz4lhTicfWkdPafR8vhqt4MIeCl-kxbMqc35UNmglzE7n-b9zVh4OhU7bSCoPKZySL5c4GSf7UFFD-mXIe6s9b4qYSXJuLpdspFJSgP7UoEGP1gh8fTb5MDZREYyZOpK3BMU8EdwokngVR9zrbw'
}

I would like to know how to store this token to be used in further calls to my API. I can see the token object in the session callback is

{ iat: 1636411862, exp: 1639003862 }

so next-aut is not doing this for me. Should I set an httpOnly cookie in the session callback? or right after

if (res.ok && user) {

just before to return user?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I found a way just updating the callbacks:

  callbacks: {
    async jwt(token, user, account, profile, isNewUser) {
      if (user?.token) {
        token.token = user.token;
      }
      return token;
    },

    async session(session, token) {
      return session;
    }
  }

in this way the token from the API is now stored in a httpOnly cookie called __Secure-next-auth.session-token (assuming the token from the API is in the format like above).

about 4 years ago · Juan Pablo Isaza Relatório

0

in dart, save the jwt token in local storage. you can then access local storage and persist the token between session.

otherwise store the jwt token in a singleton or a provider and assess it during the session.

about 4 years ago · Juan Pablo Isaza Relatório

0

If you store the JWT in the cookies so every time you're calling your API you could check the cookie header to see if you have it.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda