Next.js Discord

Discord Forum

Detect the executed server action in middleware

Answered
Youssef posted this in #help-forum
Open in Discord
How can I know which server action is being executed in the middleware?

for example I have this middleware function:
export async function middleware(request: NextRequest) {
  if (request.method === "POST") {
    // Do something
  }
}

The above condition fulfills for all server actions which isn't what I want
I want a condition that specifies one server action (let's call it login)

Any suggestions?
Thanks in advance.

edit: Can I get the request body in middleware?
Answered by Youssef
Nope, but I got a new idea to do what I wanted other than detecting the server action in middleware
View full answer

7 Replies

Masai Lion
export async function middleware(request: NextRequest) {
  if (request.method === "POST" && request.path === "/api/login") {
    // Do something
  }
}


This code above checks if the request method is POST and the path is /api/login (as you mentioned) As for accessing the request body in middleware, you can use request.body. This assumes that the request body is in JSON format. Giving us a final code that goes like this this:

export async function middleware(request: NextRequest) {
  if (request.method === "POST" && request.path === "/api/login") {
    const requestBody = await request.body.json();
    // Do something 
  }
}


@Youssef
Masai Lion
@Youssef everything alright?
@Masai Lion <@844681311490277426> everything alright?
Nope, but I got a new idea to do what I wanted other than detecting the server action in middleware
Answer
@Youssef Nope, but I got a new idea to do what I wanted other than detecting the server action in middleware
Masai Lion
Alr then can you mark the forum as solved with this your message?