Detect the executed server action in middleware
Answered
Youssef posted this in #help-forum
YoussefOP
How can I know which server action is being executed in the middleware?
for example I have this middleware function:
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
Any suggestions?
Thanks in advance.
edit: Can I get the request body in 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
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
@Youssef How can I know which server action is being executed in the middleware?
for example I have this middleware function:
ts
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?
No you can't get a specific server action based on the name of the function alone.
However you can filter usage of server action based on where it is executed
like @Masai Lion's code snippet
Masai Lion
@Youssef everything alright?
@Masai Lion <@844681311490277426> everything alright?
YoussefOP
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?