Closed 5-tom closed 4 months ago
I found a solution. Move the check to a preValidation option:
const opts = {
schema: {
consumes: ["multipart/form-data"],
body: FORM_SCHEMA
},
preValidation: (req, reply, done) => {
const auth = getAuth(req);
if (!auth.userId) {
return reply.code(403).send();
}
done();
}
};
// ...
fastify.post("/form", opts, // ...
Hello @5-tom,
Your solution is correct (you should also keep the hookName: "onRequest"
). To give you more context, the clerkPlugin
registration on the onRequest
hook means that the Clerk middleware responsible for determining the state of the request is executed before the body is parsed/validated. The Clerk middleware does not enforce the requests to be authenticated, it identifies the state and leaves the handling to the implementor using the getAuth(req)
and checks.
Preliminary Checks
[X] I have reviewed the documentation: https://clerk.com/docs
[X] I have searched for existing issues: https://github.com/clerk/javascript/issues
[X] I have not already reached out to Clerk support via email or Discord (if you have, no need to open an issue here)
[X] This issue is not a question, general help request, or anything other than a bug report directly related to Clerk. Please ask questions in our Discord community: https://clerk.com/discord.
Reproduction
https://stackblitz.com/edit/stackblitz-starters-x6zbd9?file=server.js
Publishable key
pk_test_d29uZHJvdXMtbGVlY2gtOTQuY2xlcmsuYWNjb3VudHMuZGV2JA
Description
Steps to reproduce:
With the following code, I'm unable to perform the authentication check before the request is validated.
Expected behavior:
The request should be checked to see if it can proceed before the request body is validated against a schema. I should get a 403 before a 400 or 500 etc.
Actual behavior:
Using my code snippet above, I get a 400 status code from zod. Status codes cannot be set after it's been sent, so I never receive a 403. The order of operations is incorrect.
It may relate to this https://github.com/clerk/javascript/issues/1350
Environment