Next.js Discord

Discord Forum

data access layer and security

Answered
Buff-collared Nightjar posted this in #help-forum
Open in Discord
Buff-collared NightjarOP
I read https://nextjs.org/blog/security-nextjs-server-components-actions and I still have some questions about security.

# Example scenario

## Folder structure:
src/data-access/user.ts
src/server/actions/user.ts


## src/data-access/user.ts
export async function setUserEmail({ userId, userEmail }: { userId: string; userEmail: string }) {
    await db
    .insert(userTable)
    .values({
      userId,
      userEmail,
    })
    .onConflictDoUpdate({
      target: userTable.userId,
      set: {
        userEmail,
      },
    });
}

## src/server/actions/user.ts
'use server;'

export async function setUserEmailUseCase(...) {
  const { session, user } = await validateRequest();
  if (!session || !user) {
    return {
      formError: 'Session or user is invalid, please log in.',
    };
  }

  await setUserEmail(...);
}


Q: I am concerned that my data-access layer can be called by the client by skipping the server action. Is this possible?
Answered by joulev
no the code in the data access layer cannot be called directly by the client.

if imported to the client, it will try to run db in the client which is not possible, and will fail during runtime.

if you want to be extra careful here and want the build to fail when you import setUserEmail to the client by mistake, you can import "server-only" in there.
View full answer

4 Replies

Answer
to remove it from the channel sidebar you can simply unfollow the thread