I am very new to Next.js. I am building a project in Next.js 13. The basic jist of the project is as follows. Client component sends data to server component, and than server component gets data from external API, server component gets data back from external URL, does some logic on it, and sends data to client components to be displayed. I am tinkering with the concept of middleware, but for some odd reason my middleware component is not responding at all. When I type "http://localhost:3000/test" I get an a 404 error. My file structure. my middleware function is very simple, it just returns a hello there json object. The middleware inside the app folder does not respond as well. It also has the same code as the one inside of 'test' folder. I thought initially that maybe its my browser that is the problem, so I tried postman and I am getting an error there as well, and not receiving a json object
2 Answers
Your middleware intercepts every single request, you probably do not want it to return that json - it's not like an API endpoint. I hadn't seen before but you've added a res with type NextApiResponse - that isn't right (because middleware isn't an API endpoint)
You'll typically want it to return either the request it was sent, or redirect it somewhere else if it hasn't passed the validation that you want (ie like the token is invalid, or something like that) either Response or NextResponse.
Eg, lifting the example from the NextJS Docs you can see the below. This would redirect the request to /home, here it would redirect all requests to home. So they actually include a matcher on the doc page (linked below) which only intercepts some requests.
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url))
}
NextJS's Docs can be found here.
When you're using middleware it's also important to remember it's not a typical serverless function, it's why you'll see some libraries or imports will not run in it because middleware needs to be super fast so you tend to want to do as little as possible in it.
If you really want to return a response with a body, instead of getting them to a page you can do:
return NextResponse.json(
{ success: false, message: 'authentication failed' },
{ status: 401 }
)
See Returning a Response specifically in that area of the documentation.
14 Comments
I solved the problem. The tutorial I was following used an older version of next which allowed navigation to a middleware. Recently, they have revoked it so now you can only have one middleware (https://nextjs.org/docs/messages/middleware-upgrade-guide)


