https://supertokens.com/docs/nodejs/modules/recipe...
# support-questions-legacy
p
n
Hi
Youre looking at the SDK reference page which is meant for function references as opposed to actual docs
p
how to used with graphql
Copy code
ts
   server.route({
      method: ['GET', 'POST'],
      url: graphqlPath,
      handler: graphql,
    })
r
for jwt verification, you can use any JWT library
again, it's in our docs.
p
Copy code
ts
  const response = await fetch(`${connectionUri}/recipe/session/verify`, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      'api-key': apiKey,
      'rid': 'session',
    },
    body: JSON.stringify({
      accessToken,
      enableAntiCsrf: false,
      doAntiCsrfCheck: false,
    }),
  })
https://app.swaggerhub.com/apis/supertokens/CDI/2.16.2#/Session%20Recipe/verifySession used thank you
r
well. You don't need to use that. Instead, you should use the node JS SDK's verifySession middleware if you are verifying the sAccessToken. If you are verifying the JWT, use any JWT lib
See the link sent by @nkshah2 above for how to use the verifySession function
it's more efficient than calling the above API yourself.
p
Copy code
ts
 verifySession()(ctx.req, ctx.reply, (res) => {
            console.log(res)
          })
thats true ?
iam in graphql server used
r
so a better function to use would be the getSession function in this case
cause you are not using the middleware like a middelware
p
Copy code
TypeError: Cannot read properties of undefined (reading 'wrapperUsed')
r
can i see the code?
p
Copy code
ts
        try {
            const session = await Session.getSession(ctx.req, ctx.res)

            if (session === undefined)
              throw new Error('Should never come here')

            const userId = session.getUserId()
            console.log(userId, 'aaa')
          }
          catch (error) {
            console.log(error, 'aaa')
          }
r
can you log out
ctx.req
and
cts.res
?
p
log out ? -> see, yes all see
r
as in console.log
console.log(ctx.req, ctx.res)
p
req data see but res empty
r
yea so thats the problem
you need to give it a response object
p
okay now fixed res.
Copy code
SessionError: Session does not exist. Are you sending the session tokens in the request as cookies?
r
are you sending the JWT from the frontend as an authorization bearer token?
right. So the
getSession
and
verifySession
functions only work for our sAccessToken cookie
since you are using a JWT, you should use any JWT verification library for your framework
p
hmm if this cookie comes in it is automatically verified right?
header etc dont verified, thats true
r
yea. So for getSession, the
sAccessToken
and
sIdRfereshToken
are required. In that case, you don't need to to send the authorization bearer token
p
Copy code
ts
 const client = jwksClient({
    jwksUri: 'http://localhost:3001/auth/jwt/jwks.json',
  })

  function getKey(header: JwtHeader, callback: SigningKeyCallback) {
    client.getSigningKey(header.kid, (err, key) => {
      const signingKey = key!.getPublicKey()
      callback(err, signingKey)
    })
  }

  console.log(token, 'token')
  JsonWebToken.verify(token, getKey, {}, (_err, decoded) => {
    const decodedJWT = decoded
    console.log(decodedJWT, 'decoded')
  })
undefined decoded
r
what is the _err?
p
JsonWebTokenError: jwt malformed
r
Can you paste the token here?
p
Copy code
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsInZlcnNpb24iOiIyIn0=.eyJzZXNzaW9uSGFuZGxlIjoiMmE0YmRiNGYtYzE2Ni00NGJiLThkZDYtNDFiN2ZkZDI5NmM5IiwidXNlcklkIjoiZmUxZGQ2OGMtNjc3NS00MzViLWE2OTgtYzFiNGUyOTk1NzAyIiwicmVmcmVzaFRva2VuSGFzaDEiOiIzNTYwNjdlM2E3Y2RhMjNhMjQzMTFiMGFlYThjMmRhODI4ZjhhMWU3NzJkYzhlMWI5M2E4NjQzYjRlMDRmMzAwIiwicGFyZW50UmVmcmVzaFRva2VuSGFzaDEiOm51bGwsInVzZXJEYXRhIjp7Imp3dCI6ImV5SnJhV1FpT2lJd056STFNR1UzT0MwM1pqTTVMVFJtTVRrdFlqWmhaQzFsWWpCbFkyWmhZalppTWpFaUxDSjBlWEFpT2lKS1YxUWlMQ0poYkdjaU9pSlNVekkxTmlKOS5leUp6ZFdJaU9pSm1aVEZrWkRZNFl5MDJOemMxTFRRek5XSXRZVFk1T0Mxak1XSTBaVEk1T1RVM01ESWlMQ0pwYzNNaU9pSm9kSFJ3T2k4dmJHOWpZV3hvYjNOME9qTXdNREV2WVhWMGFDSXNJbVY0Y0NJNk1UWTNNRGt5TVRreE55d2lhV0YwSWpveE5qY3dPVEU0TWpnMmZRLlNSTzdaTUNvbzFHNWNFWWZOdG1jRGRWRjdLZHdKSDJxLUtIMXM1eTBkZGt1bDRvNVVLQ01MUkhZZDdES2tzNDVwbnB1VzJaY0JHZVMwaFpxam11b2JrQktSWW9jcFRKTjdiNnYtOGt3czBsZHY2RFdMTk5mSlplQmlPSHlSS1E4OUo4ZXYwTVpFcW1HM2VPNUUxdjhCMHJNeFVKbk1VVHQtYjNmaTA2VGY1UzJTZy1VQkFaWkhPbHhHemVtYWU4eWliM1FDc1kzX1VIMkpPVGJRZnZVbDVmN0h2UjVQUi1QQ2ZWMkltWUFVckNReGp4WVdjZmtETXdZWDlfMXp5ZHN0NmNCV3dIV2J5WlRtTTZrdjFXbldwTDJzbUFJYklvMzhHdmdScE1xbUN1ai0wSVowcGUxT05SWHdyaEJxWW5zYWVQX2x4NzZQMWhhTWFwTWlpMFFOQSIsIl9qd3RQTmFtZSI6Imp3dCJ9LCJhbnRpQ3NyZlRva2VuIjpudWxsLCJleHBpcnlUaW1lIjoxNjcwOTIxODg2OTIxLCJ0aW1lQ3JlYXRlZCI6MTY3MDkxODI4NjkyMSwibG1ydCI6MTY3MDkxODI4NjkyMX0=.PCde9q7C173dbbR17ICZu2lgtp/rPpHWvMinF5rbhAS+YFfOCcopvjQImLPjKCH2zOZPO/wRPk2n7FTvAJo42kpWg0RGiv9X7MYA5UCYwylYCJZI6zGZvJi2te1XV+MU2hAMuuM5TbcwdHWmPVFCAl5PtfMAH7R8UpnBei4cma0TZN1nRsK73hesQsVHSknDBOw4dYDBCRRfz78Fi1GnBYU9XMpf1e/WTcDfMMq1WZI31NnmzYVIsH6o7EBKM3g+eat3O2P+6hFTKlp7fafA2xqb+gFFJqd+SqiHOlX2peCQpRc0PDDFp/zgADVhAXHbug1cc4b5vjjOAtUdDY5JiQ==
r
right. So you are giving it the sAccessToken
you need to give it the authorization bearer token from the request
the thing you added on the frontend when querying this API
p
this ?
same token
r
no.
so on the frontend, you add the JWT to the request right?
as an authorization bearer token
correct?
p
yes
r
so you should read that on the backend from the request and use that as the token for the JWT verification
p
Copy code
ts
   if (ctx.headers.authorization) {
            let authHeader = ctx.headers.authorization
            authHeader = Array.isArray(authHeader) ? authHeader[0] : authHeader

            const authHeaderParts = authHeader.split(' ')
            if (authHeaderParts.length === 2 && authHeaderParts[0] === 'Bearer') {
              const accessToken = authHeaderParts[1]
              verifyToken(accessToken)
         
            }
          }
and back
r
right yea
p
this same
r
are you querying the APi using postman?
i mean testing the API using postman*
p
no nuxt reload page and backend console see
r
im not sure how to make this more clear
but you are passingt he sAccessToken to the JWT verification which will get that issue about JWT malformed
you need to see your code about which token you are passing where
the authorization bearer token is the JWT not the sAccessToken
p
Copy code
ts
     Session.init({
        jwt: {
          enable: true,
        },
      }),
and login
sAccessToken -> this jwt thats true
r
sAccessToken is not the JWT. The JWT is in the sAccessToken payload which you extract on the frontend and pass the authorization header to the backend
p
hmm
Copy code
const jwt = await Session.getAccessTokenPayloadSecurely().jwt
only get jwt
clinet and send server
Copy code
eyJraWQiOiIwNzI1MGU3OC03ZjM5LTRmMTktYjZhZC1lYjBlY2ZhYjZiMjEiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJmZTFkZDY4Yy02Nzc1LTQzNWItYTY5OC1jMWI0ZTI5OTU3MDIiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjMwMDEvYXV0aCIsImV4cCI6MTY3MDkyMzg2MywiaWF0IjoxNjcwOTIwMjMyfQ.faEnRZMQDV_OpGb0B8hWJZNd8YmaRBWPIiVP5VSrrud6db92htxTKza7PiAAYGfFE6jzBr_EILy3PEXGwpVGzisaERqcyi09nCIwjngDhuW9S8HCsjKpwW75EWyylUAYtsYsa63ggnyGBhP2r9NOlrSb92OwrYT_eNRe-EFZjLbkXsh69NNZAhngzqnNBf3o6G2zEpqLsq3UmL8P_321fKDL6T1cZj3J_4bdPsmwwmruOqtxHgEGsulokUx_IMBhE_oqzTTKPYhnSMF9JGZaaX2kaZ50Mx8uLkBcQwEyMthsJZ-pmH9MUH75azXG_t6TaX5vxkUa8MCmIjSogoh1eg
this
The big problem is I can't figure out how to send it with nuxt 3. Because graphql structure I can't get it in advance.
r
are you talking about server side rendering?
cause for SSR, you will have to use cookies - in which case, you can use the getSession function.
p
how to login after save
getAccessTokenPayloadSecurely
jwt save cookie ?
why not retroactive direct jwt freeze
After logging in, if we save the cookie without the need for jwt http secure, the problem will disappear.
After all, you don't need http secure for jwt, right?
r
i don't think i understand your question here.
anyway, hope you can figure it out 🙂
p
Why is jwt direct cookie not saved after login even though I selected jwt?
r
Cause if you want to use cookie based auth, you don't need to use JWT. just use the sAccessToken and use the getSession function we have. That's all
p
Shouldn't jwt be registered here directly?
r
no
cause the purpose the JWT is different
p
how to only jwt used ?
r
we don't have an option (yet) of how to only get JWT in cookies
we provide the sAccessToken which can be used along with our SDK
So maybe just use that instead of using the JWT method
p
I can't use it because access to it is late on the client side in ssr and the api sends a request without waiting for it.
this is why jwt and other cookies are not received
r
what do you mean access to is late?
p
Copy code
ts
import {
  ApolloClient,
  InMemoryCache,
  createHttpLink,
} from '@apollo/client/core/index.js'
import {
  DefaultApolloClient,
  provideApolloClient,
} from '@vue/apollo-composable/dist/index.esm.js'
import Session from 'supertokens-web-js/recipe/session'
import SuperTokens from 'supertokens-web-js'
import ThirdPartyEmailPassword from 'supertokens-web-js/recipe/thirdpartyemailpassword'
import { defineNuxtPlugin } from '#app'

export default defineNuxtPlugin(async (nuxtApp) => {
  let token = ''
  console.log('1')
  nuxtApp.hook('app:mount
ed', async () => {
    console.log('2')
    SuperTokens.init({
      appInfo: {
        apiDomain: 'http://localhost:3001',
        apiBasePath: '/auth',
        appName: 'aa',
      },
      recipeList: [
        Session.init(),
        ThirdPartyEmailPassword.init(),
      ],
    })
    console.log('3')

    Session.getAccessTokenPayloadSecurely().then((payload) => {
      token = payload.jwt
    })
    console.log('4')
  })
  console.log('5')

  const httpLink = createHttpLink({
    credentials: 'include',
    uri: 'http://127.0.0.1:3001/graphql',
    headers: {
      authorization: `Bearer ${token}`,
    },
  })

  const cache = new InMemoryCache()

  let apolloClient: ApolloClient<any>

  if (process.server) {
    console.log('6')
    apolloClient = new ApolloClient({
      ssrMode: true,
      link: httpLink,
      cache,
    })
    nuxtApp.hook('app:rendered', () => {
      nuxtApp.payload.data.apollo = apolloClient.extract()
    })
  }
  else {
    console.log('7')
    apolloClient = new ApolloClient({
      link: httpLink,
      cache,
      ssrForceFetchDelay: 100,
    })
  }

  provideApolloClient(apolloClient)
  nuxtApp.provide('$apollo', { DefaultApolloClient, apolloClient })
})
r
once you login, we add the sAccessToken to the cookies
which would be sent on each API call
p
I gave console.log numbers, you can understand from here
9-vue-index
-> index.vue data send
r
im not sure why you even need to do this:
Copy code
Session.getAccessTokenPayloadSecurely().then((payload) => {
      token = payload.jwt
    })
the access token cookie should go in the request header
which the browser would add automatically
if that's not happening, you should see why.
you really don't need to use the authorization header at all
it's much simpler with just cookies and the getSession function.
what is the value of apiDomain that you have set in supertokens.init?
p
backend
r
and on the frontend?
p
Copy code
SuperTokens.init({
      appInfo: {
        apiDomain: 'http://localhost:3001',
        apiBasePath: '/auth',
        appName: 'aaa',
      },
      recipeList: [
        Session.init(),
        ThirdPartyEmailPassword.init(),
      ],
    })
r
right. So the reason the cookies don't go is cause you have set this to localhost, but the graphql is being queried via 127.0.0.1.
So either change the apiDomain on frontend and backend to 127.0.01:3001, or then change the graphql requests to use localhost:3001
p
all change localhost -> 127.0.01
r
did you sign in?
p
yes
r
are you sure?
p
logout and re login
dont fixed
r
whats the cookie store on the frontend after you logged in?
p
🔥
r
ok great!!
p
Thank you very much, very very much
r
now on thje backend, you can use the getSession function like you were before
p
👏
r
so it works?
p
yes
r
nice
p
Copy code
const session = await Session.getSession(ctx.req, ctx.reply)
          await verifyToken(session.getAccessTokenPayload().jwt)
now token verify working 👏
r
right. So you don't need to call
verifyToken
at all.. cause
Session.getSession
does verification.
and you can even disable the JWT config
3 Views