Skip to content

Improve Cookie Plugin Registration to Avoid Decorator Conflicts: FastifyError: The decorator 'serializeCookie' has already been added! error #28

@channainfo

Description

@channainfo

Description

When using @adminjs/fastify with other Fastify plugins like @fastify/oauth2 that also manage cookies, I encountered a FastifyError: The decorator 'serializeCookie' has already been added! error. This happens because buildAuthenticatedRouter internally registers @fastify/cookie without checking if it’s already initialized in the Fastify instance.

In contrast, @fastify/oauth2 checks for existing cookie initialization and skips registration if the serializeCookie decorator is present, avoiding conflicts. This behavior difference forces users to carefully order plugin registrations (e.g., loading AdminJS before OAuth2) to avoid errors, which isn’t ideal.

Steps to Reproduce

  1. Set up a Fastify app with @fastify/cookie and @fastify/session at the root level.
  2. Register @fastify/oauth2 for Google/GitHub authentication.
  3. Register @adminjs/fastify with buildAuthenticatedRouter.
  4. Run the app and observe the serializeCookie decorator conflict.

Expected Behavior

@adminjs/fastify’s buildAuthenticatedRouter should check if @fastify/cookie (or its decorators like serializeCookie) is already registered in the Fastify instance and skip registration if present, similar to @fastify/oauth2.

Actual Behavior

buildAuthenticatedRouter unconditionally registers @fastify/cookie, causing a decorator conflict if another plugin or the root app has already done so.

Suggested Fix

  • Add a check in buildAuthenticatedRouter (or its internal setup) to detect existing fastify.cookie or serializeCookie decorator:
    // https://github.com/SoftwareBrothers/adminjs-fastify/blob/main/src/buildAuthenticatedRouter.ts#L76C2-L78C6
    if (!fastify.hasReplyDecorator('serializeCookie')) {
        await fastifyApp.register(fastifyCookie, {
            secret: auth.cookiePassword,
        });
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions