Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
How to redirect for Next.js middleware sub-directory?

I would like to redirect users in my middleware. However, Next.js middleware behaves inconsistently. If I place the middleware in /pages/_middleware.ts the redirect will work. If I place it in /pages/api/_middleware.ts the redirect will not work.

// /pages/_middleware.ts
export function middleware() {
  return NextResponse.redirect(
    `http://example.com`
  );
}
// /pages/api/_middleware.ts
export function middleware() {
  return NextResponse.redirect(
    `http://example.com`
  );
}

Update:

I did a test on a fresh project for /api. The user will be redirected if they direst navigate to the route /api/hello. However, when the request is made via code redirect will fail. I would like to add a redirect guard at the api level but this doesn't seem possible with _middleware.

fetch(
  `/api/hello`,
  {
    credentials: 'same-origin',
    method: 'POST',
  }
);
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!