Next.js Discord

Discord Forum

How to return directly from middleware in next-safe-actions

Answered
Anay-208 posted this in #help-forum
Open in Discord
I'm using next-safe-actions [middleware](https://next-safe-action.dev/docs/safe-action-client/using-a-middleware), however, I m trying to detect on middleware about recaptcha verification, however, if it fails, I just want it to return to the client. How can I do that as I don't see any docs for it?

I tried to do this
import { createSafeActionClient } from "next-safe-action";
import { cookies } from "next/headers";

interface MiddlewareData  extends Record<string, any> {
    recaptcha: string;
};

export const recaptchaAction = createSafeActionClient({
  // If you need to access validated input, you can use `parsedInput` how you want
  // in your middleware. Please note that `parsedInput` is typed any, as it
  // comes from an action, while middleware is an (optional) instance function.
  // Can also be a non async function.
  async middleware(parsedInput, data ?: MiddlewareData) {
    if(!data?.recaptcha){
        return {recaptcha: false}
    }
    

    return {recaptcha: true};
    // ...
  },
});

login.ts
import { initiateUserRegistrationByEmail } from "@/lib/db";
import { z } from "zod";
import { recaptchaAction } from "@/lib/safe-actions/recaptcha";

const schema = z.object({
  email: z.string().email({ message: "Invalid email address" }),
  name: z.string()
    .min(3, { message: "Name must be at least 3 characters long" })
    .max(70, { message: "Name must be no more than 70 characters long" }),
});

type Schema = z.infer<typeof schema>

export const login = recaptchaAction(schema, async ({email, name} : Schema) => {
      console.log("login executed")
      const data = await initiateUserRegistrationByEmail(email, name);
      if (data.insertedId) {
        return { success: true }
      } else {
        return { success: false }
    }
}, { middlewareData: {recaptcha: true}})

However, I see a warning so I'm expecting this code to throw an error
Answered by Anay-208
According to the docs, I don't think any other way is available. I passed the middleware data to the server action and verified there
View full answer

2 Replies

Bump
According to the docs, I don't think any other way is available. I passed the middleware data to the server action and verified there
Answer