Next.js Discord

Discord Forum

How to fetch data in middleware?

Unanswered
Minskin posted this in #help-forum
Open in Discord
MinskinOP
Whenever i try to fetch data from my middleware, using fetch, to check if the session is valid, i get a weird error:
TypeError: Cannot read properties of undefined (reading 'substring')

How can this be fixed?

1 Reply

MinskinOP
import { withAuth } from "next-auth/middleware"
import { baseURL } from "./app/api/backend"

export default withAuth(() => {

},{
  callbacks: {
    async authorized({token}) {
      console.log(token)

      if (!token) return false
      const isValid = await isSessionValid(token.accessToken)


      return isValid
    }
  }
})

const isSessionValid = async(token: string): Promise<boolean> => {
  console.log(token)
  const res = await fetch(`${baseURL}/auth/`, {
    headers: {
      "Authorization": token
    }
  })

  return res.status === 200
  return true
}

export const config = { matcher: ['/dashboard'] }
`