I need a middleware in my nextjs project which is a monorepo (frontend and backend in the same project) and I need to intercept the requests through a middleware and do the stuff I basically do in every API: authentication and other controls. I took a look to this but I can't figue out how to get the actual request (headers, body, query string etc).
So I created the file _middleware.ts
under the /pages
folder and this:
import type { NextFetchEvent, NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
export async function middleware(req: NextRequest, ev: NextFetchEvent) {
console.log('request - - -- - >', req);
}
I thought in req
parameter I had the entire request but I didn't. In fact, if I log it I get this result:
NextRequestHint [Request] {
sourcePage: '/_middleware',
[Symbol(internal body)]: { bodyInit: null, disturbed: false },
[Symbol(internal request)]: {
credentials: 'same-origin',
headers: BaseHeaders [Headers] { [Symbol(map)]: [Object] },
method: 'GET',
referrer: 'about:client',
redirect: 'follow',
url: NextURL { [Symbol(NextURLInternal)]: [Object] }
},
[Symbol(internal request)]: {
cookieParser: [Function: cookieParser],
geo: {},
ip: undefined,
page: { name: '/[user]', params: [Object] },
url: NextURL { [Symbol(NextURLInternal)]: [Object] }
}
}
Is there a way to get the entire request here? Or is there another way in doing a middleware where I can do the general things I do for every API? thank you.
version nextjs: 12.0.9
CodePudding user response:
The NextRequest
class extends a Request
interface which is based on its native counterpart. You can see the different properties available to you in the following files:
node_modules/next/dist/server/web/spec-extension/request.js
node_modules/typescript/lib/lib.dom.d.ts
Accessing them would look something like this:
// pages/api/_middleware.ts
import type { NextFetchEvent, NextRequest } from "next/server";
import { NextResponse } from "next/server";
const streamToString = async (stream: ReadableStream<Uint8Array> | null) => {
if (stream) {
const chunks = [];
for await (const chunk of stream) {
chunks.push(Buffer.from(chunk));
}
return Buffer.concat(chunks).toString("utf-8");
}
return null;
};
export async function middleware(req: NextRequest, ev: NextFetchEvent) {
console.log("Method:", req.method);
console.log("Content-Type:", req.headers.get("content-type"));
console.log("Route:", req.nextUrl.pathname);
console.log("Query String:", req.nextUrl.search);
console.log("Query Parameters:", req.nextUrl.searchParams);
console.log("Body:", await streamToString(req.body));
// do your stuff
return NextResponse.next();
}