req.query is undefined when used in middleware
Unanswered
Gazami crab posted this in #help-forum
Gazami crabOP
Hi, i'm trying to make simple middleware to check api-key:
I have created middleware.js in the root folder as explained in https://nextjs.org/docs/pages/building-your-application/routing/middleware
middleware.js:
But
I have created middleware.js in the root folder as explained in https://nextjs.org/docs/pages/building-your-application/routing/middleware
middleware.js:
export function middleware(request, response) {
console.log('request:', request.query)
const { api_key } = request.query; // request.query is undefined
const isAuthenticated = (api_key === process.env.API_KEY)
if (!isAuthenticated) {
return Response.json(
{ success: false, message: 'Api key is wrong' },
{ status: 401 }
)
}
}But
request.query is undefined, so it is not work. How to solve it? It works ok in api routes but return an error for middleware