Next.js Discord

Discord Forum

How to get JWT token for my websocket connection?

Unanswered
Finnish Spitz posted this in #help-forum
Open in Discord
Finnish SpitzOP
import { useSession } from 'next-auth/react'
import { io, Socket } from 'socket.io-client'
import { getServerAuthSession } from '~/app/api/auth/[...nextauth]/route'
// import { getServerAuthSession } from '~/app/api/auth/[...nextauth]/route'

let socket: Socket | null = null

export const connectSocket = async (): Promise<Socket> => {
  const session = useSession()
  const session2 = await getServerAuthSession()
  if (socket) return socket

  console.log(session)

  const token =
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MywiYWRtaW5fdW5pdl9pZCI6bnVsbCwiaXNfc3VwZXJfYWRtaW4iOnRydWUsInJvbGUiOiJBRE1JTiIsImlhdCI6MTc1MjczOTI4NSwiZXhwIjoxNzUyNzQwMTg1fQ.o5SNlPOLVaB9vOBk9I3LfRKm3OFTmUBHKPxBWkNOqEg'

  socket = io('http://localhost:8080' as string, {
    extraHeaders: {
      Authorization: `Bearer ${token}`,
    },
  })

  return socket
}

export const getSocket = (): Socket | null => socket


how to send my jwt token from client to server in nextauth and nextjs, i tried using client (useSession) and server side (getServerAuthSession), my page is error. What is the best practice to setup websocket for nextjs case + jwt token

0 Replies