Ali EXE
Ali EXE

Reputation: 1361

How to use async custom hook in Next.js middleware?

I have this custom hook:

const useRedirects = async () => {

    const response = await fetch('/redirect/list') 
    const redirects = await response.json()

    const checkRedirection = (url) => {
       return {
           isRedirected: // logic to check redirection
           newUrl: // logic to form the new URL
       }
    }

    return {
        checkRedirection
    }
}

export default useRedirects

And this is my middleware.js code:

import { NextResponse } from 'next/server'
import { useRedirect } from './UseRedirect'

export async function middleware(request) {

    if (request.nextUrl.pathname.startsWith('/_next')) {
        return
    }

    const checkRedirection = await useRedirect()

    const { isRedirected, newUrl } = checkRedirection(request.nextUrl)
    
    if (isRedirected) {
       return newUrl
    }
}

The problem is that, I get this error:

TypeError: Cannot read properties of null (reading 'length') at eval (webpack-internal:///../../next/node_modules/next/dist/client/dev/error-overlay/hot-dev-client.js:262:55) error - ../next/node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js (461:0) @ error - document is not defined

So, how can I use an async hook inside my next.js middleware?

Upvotes: 0

Views: 1682

Answers (1)

Seong Jin Kim
Seong Jin Kim

Reputation: 131

Take a look at this!

https://nextjs.org/docs/app/building-your-application/routing/middleware#waituntil-and-nextfetchevent

import { NextResponse } from 'next/server'
import type { NextFetchEvent, NextRequest } from 'next/server'
 
export function middleware(req: NextRequest, event: NextFetchEvent) {
  event.waitUntil(
    fetch('https://my-analytics-platform.com', {
      method: 'POST',
      body: JSON.stringify({ pathname: req.nextUrl.pathname }),
    })
  )
 
  return NextResponse.next()
}

Upvotes: 0

Related Questions