Next.js Discord

Discord Forum

Server actions returning undefined

Answered
Mugger Crocodile posted this in #help-forum
Open in Discord
Mugger CrocodileOP
I have a server action that receives a form from the client, stores the data into the database, and then return the data and status for the client. But the action keeps returning undefined.
Answered by joulev
Uh no. The config should be this
export const config = {
  matcher: [
    {
      source: "/((?!api|_next/static|_next/image|favicon.ico).*)",
      missing: [
        { type: "header", key: "next-router-prefetch" },
        { type: "header", key: "next-action" },
        { type: "header", key: "purpose", value: "prefetch" },
      ],
    },
  ],
};
View full answer

25 Replies

type CreationResult =
  | {
      error: string;
      interviewer?: undefined;
    }
  | {
      interviewer: {
        id: bigint;
        name: string;
        userId: bigint;
      };
      error: null;
    };

export async function create(data: FormData): Promise<CreationResult> {
  const session = await auth();

  if (!session) {
    return {
      error: "Não autorizado",
    };
  }

  const user = session.user as User;

  if (!user.permissions.includes("interviewer:create"))
    return {
      error: "Usuário não tem as permissões necessárias",
    };

  const validatedFields = await interviewerCreationSchema.safeParseAsync({
    name: data.get("name"),
    username: data.get("username"),
    password: data.get("password"),
  });

  if (!validatedFields.success) {
    return {
      error: fromError(validatedFields.error).toString(),
    };
  }

  try {
    const user = await repository.user.create({
      data: {
        kind: "Interviewer",
        username: validatedFields.data.username,
        password: await bcryptjs.hash(
          validatedFields.data.password,
          await bcryptjs.genSalt(12)
        ),
        interviewer: {
          create: {
            name: validatedFields.data.name,
          },
        },
      },
      include: {
        interviewer: true,
      },
    });

    return {
      interviewer: user.interviewer!,
      error: null,
    };
  } catch (err) {
    if (err instanceof Prisma.PrismaClientKnownRequestError) {
      if (err.code === "P2002") {
        return {
          error: "Nome de usuário já existe",
        };
      } else {
        return {
          error: `Erro no servidor não identificado (${err.code})`,
        };
      }
    }
  }

  return {
    error: "Erro interno no servidor",
  };
}
Turkish Van
Just a pro tip when sending a code snippet. Try wrapping it like this:
@Turkish Van Just a pro tip when sending a code snippet. Try wrapping it like this:
Mugger CrocodileOP
Thanks, Sorry for not using It earlier, I am not used to discord
Mugger CrocodileOP
import { auth } from "@/auth";
import { NextResponse } from "next/server";

export default auth((req) => {
  const requestHeaders = new Headers(req.headers);

  requestHeaders.set("x-pathname", req.nextUrl.pathname);

  return NextResponse.next({
    headers: requestHeaders,
  });
});

// Optionally, don't invoke Middleware on some paths
export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
oh
@joulev Add more things to the config object: https://github.com/vercel/next.js/issues/50659#issuecomment-1846046743
Mugger CrocodileOP
do you have an example implementation of generateNonce and generateCSP?
@Mugger Crocodile do you have an example implementation of `generateNonce` and `generateCSP`?
Ignore their middleware content. Just add the missing property to the exported config object
Those functions are specific to their apps
Mugger CrocodileOP
The problem persists, unfortunately
Should we make a discord call or something?
Show your new middleware
Mugger CrocodileOP
import { auth } from "@/auth";
import { NextResponse } from "next/server";

export default auth((req) => {
  const requestHeaders = new Headers(req.headers);

  requestHeaders.set("x-pathname", req.nextUrl.pathname); 

  return NextResponse.next({
    headers: requestHeaders,
    request: {
      headers: requestHeaders,
    },
  });
});

// Optionally, don't invoke Middleware on some paths
export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
  missing: [
    { type: "header", key: "next-router-prefetch" },
    { type: "header", key: "next-action" },
    { type: "header", key: "purpose", value: "prefetch" },
  ],
};
Answer
Mugger CrocodileOP
Now it works
Thank you
:sunglasses_1:
doesnt that j disable the middleware for routes with server actions
Nevermind I found the solution to keep the server action working but also maintain middleware incase u use it for security
do {request: {headers: headersObject}}