0

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

File structure

Browser

middleware code

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

14 Comments

point noted, but why am I not getting a json response back on the localhost:3000/test route? I should be seeing a json object at least. I was planning on having one middleware at the root, and than redirect it to other server components where data will be fetched from a API, but when I had middleware at the root, I didnt get a response, so I tried a test route and put middleware inside the test folder to see if it would work, and it doesnt work. What explains that?
Yes, you will only have 1 middleware and that can have branching logic. But it's a bit weird to make that middleware your router. Also, "other sever components" middleware is not a server component - it's a serverless edge function with a stripped down run time. With your middleware the way it is, returning that JSON, your middleware is preventing the req.url from getting passed through. It's causing an error 'during' the request for want of a better word.
understood, but what explains me not getting a json object back at the /test url link?
Middleware return type isn't right here that may have misled you. I'm fairly sure req.status isn't a function so that will be the cause of the error. If you want to return a response you just want to return return Response.json( { success: false, message: 'authentication failed' }, { status: 401 } ) See nextjs.org/docs/app/building-your-application/routing/…
I did what you said, but I am still getting 404 on the /test url. I just commented out the res.status(200).json..... part and replaced it with "Response.json({test:"TESTING!!", message:"I hope this works"})" , I am still getting nothing
|
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.