CodingNic

Personalize the Reading Experience

Build the Preferences API

Personalize the Reading Experience 15 min read

Build the Preferences API

Build the Preferences API

Task

Create an authenticated endpoint for reading and updating ReaderPreference.

Route

Create:

text
app/api/preferences/reader/route.ts

Load the current user’s preference record:

ts
const preference = await prisma.readerPreference.findUnique({
  where: { userId: user.id },
});

Update with an ownership predicate represented by the unique userId relation:

ts
await prisma.readerPreference.upsert({
  where: { userId: user.id },
  create: {
    userId: user.id,
    theme,
    fontFamily,
    fontSize,
    lineHeight,
    contentWidth,
  },
  update: {
    theme,
    fontFamily,
    fontSize,
    lineHeight,
    contentWidth,
  },
});

Validate every value before persisting it.

Test

GET the preferences, update one setting, reload, and GET again.

Checkpoint

Reader preferences have a user-scoped persistence boundary.