Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
}
like image 914
Mohammad Miras Avatar asked Sep 17 '25 10:09

Mohammad Miras


1 Answers

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)
like image 98
Brandon Garcia Avatar answered Sep 20 '25 00:09

Brandon Garcia