Next.js Discord

Discord Forum

Is it possible to fetch data in middleware ?

Unanswered
Saint Hubert Jura Hound posted this in #help-forum
Open in Discord
Saint Hubert Jura HoundOP
I want fetch data in my middleware but it doesn't work...
export default withAuth(
  async function middleware(req) {
    const { token } = req.nextauth

    if (token && !token.username) {
      const result = await fetch(`http://localhost:3000/api/user/username`)
      const { username } = await result.json()

      if (!username) {
        const callbackUrl = req.nextUrl.pathname
        return NextResponse.redirect(
          new URL(
            `/username?callbackUrl=${encodeURIComponent(callbackUrl)}`,
            req.url
          )
        )
      }
    }
  },
  {
    pages: {
      signIn: '/login'
    }
  }
)

0 Replies