Skip to content

Elysia Response Validation Fails to Serialize Dates from Effect Schema, Zod (and Potentially Other Libraries) #1670

@Vicentesan

Description

@Vicentesan

What version of Elysia is running?

1.4.21

What platform is your computer?

Darwin 25.3.0 arm64 arm

What environment are you using

Bun 1.3.5

Are you using dynamic mode?

no

What steps can reproduce the bug?

  1. Clone the repository https://github.com/Vicentesan/elysia-openapi-issue-with-dates/tree/vicentesan/effect-ts (the branch must be vicentesan/effect-ts)
  2. Install the dependencies via bun install
  3. Run the server via bun run dev
  4. Make a GET request to localhost:8080

What is the expected behavior?

Instead of manually working around each validation library, I think Elysia should convert the date and datetime into ISO format by default

What do you see instead?

{
  "type": "validation",
  "on": "response",
  "property": "root",
  "message": "Expected string, actual 2026-01-10T20:07:52.545Z",
  "found": "2026-01-10T20:07:52.545Z",
  "errors": [
    {
      "path": [],
      "message": "Expected string, actual 2026-01-10T20:07:52.545Z"
    }
  ]
}

Additional information

This also occurs with Zod; the workaround is as follows:

import { Elysia } from 'elysia';
import { openapi } from '@elysiajs/openapi'
import z, { type ZodType } from 'zod';

const overrideJSONSchema = <T extends ZodType>(
  schema: T,
  toJSONSchema: () => unknown | undefined,
) => {
  schema._zod.toJSONSchema = toJSONSchema

  return schema
}

const datetime = z.union([
    z.iso.datetime(),
    z.date()
  ]);

export const zDate = overrideJSONSchema(
  z.codec(datetime, datetime, {
    decode: (isoString) => new Date(isoString),
    encode: (date) => new Date(date).toISOString(),
  }),
  () => z.toJSONSchema(z.iso.datetime()),
)

const app = new Elysia()
  .use(openapi({
    mapJsonSchema: {
      zod: z.toJSONSchema
    }
  }))
  .get(
    '/date',
    async ({ status }) => {
      const date = new Date();

      return status(200, { date });
    },
    {
      response: {
        200: z.object({ date: zDate })
      }
    }
  )
  .listen(8080);

Have you try removing the node_modules and bun.lockb and try again yet?

yes

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions