A Data Access Layer
Server code and client code live in the same repository, so the risk is accidental imports: a database client or an authorization check that leaks into a Client Component. A Data Access Layer (DAL) removes the guesswork by putting all server-only data access behind one module.
// lib/data.ts
import 'server-only';
export async function getCurrentUser() {
const session = await auth();
if (!session) throw new Error('Unauthorized');
return db.user.findUnique({ where: { id: session.userId } });
}
Two things make it work. The import 'server-only' marker makes the build fail if
the module is ever pulled into a Client Component, so the DAL cannot be shipped to
the browser. And because every read and write goes through this module, the
authorization check lives in one place — a Server Function or page calls
getCurrentUser() and cannot forget to check who is asking, because the check is
inside the function it already calls.
This is defense in depth: the boundary keeps secrets off the client, and the DAL keeps authorization out of the client's reach. Both matter, because a Server Function is a public endpoint — anyone can call it, so the trust decision belongs on the server, in code the client cannot reach.
// app/actions.ts
'use server';
import { getCurrentUser } from '@/lib/data';
export async function renameMe(name: string) {
const user = await getCurrentUser(); // authz enforced here
return db.user.update({ where: { id: user.id }, data: { name } });
}
You are about to answer a short quiz on server-only data access.