Mohammad Miras
Mohammad Miras

Reputation: 604

How to Use fetch Api in Middleware nextjs

I am using one middleware in nextjs (https://nextjs.org/docs/advanced-features/middleware)

But I can't send a request to the api And the error it shows me

unhandledRejection: TypeError: Cannot delete property 'Symbol(set-cookie)'

enter image description here

My miidleware.js

import { get } from 'Base'
import { redirect } from 'next/dist/server/api-utils'
import { NextResponse } from 'next/server'

export async  function middleware(req) {


  const data = await fetch(process.env.NEXT_PUBLIC_API_BASE+"/seosite/getallredirect" )
  console.log(data )

  const { pathname ,origin } = req.nextUrl

  const redirect = data?.redirects?.find(i.oldUrl == pathname);

  if(redirect){
      if(redirect?.code == 301 || redirect?.code == null  )
         return NextResponse.redirect(origin+redirect.oldUrl)
  }

  return NextResponse.next()
}

Upvotes: 4

Views: 22328

Answers (1)

Brandon Garcia
Brandon Garcia

Reputation: 84

You have to convert the response into json

 const data = await (await fetch(process.env.NEXT_PUBLIC_API_BASE+"/seosite/getallredirect")).json()
  console.log(data)

Upvotes: 6

Related Questions