[GH-ISSUE #5293] Cookie cache from signup / signin routes do not respect additionalFields[key].returned option #10206

Closed
opened 2026-04-13 06:11:34 -05:00 by GiteaMirror · 1 comment
Owner

Originally created by @vnphanquang on GitHub (Oct 14, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/5293

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

Issue can be observed by adding & running the following test case to packages/better-auth/src/cookies/cookies.test.ts, adapted from the last test in the suite.

The impact this has for my particular use case is that because one of my additional field is very large in size, cookie cache fails to be applied until the first getSession, which does correctly filter out said field.

Important

Please notice this line: expect(sizeError).toBeUndefined(); that should pass but is currently failing as of ^1.3.27 in stable release, or 1.4.0-beta.9 in canary.

it.only("should correctly filter fields based on configuration", async () => {
	const loggerErrors: string[] = [];
	const mockLogger = {
		log: (level: string, message: string) => {
			if (level === "error") {
				loggerErrors.push(message);
			}
		},
	};

	const { auth } = await getTestInstance({
		secret: "better-auth.secret",
		user: {
			additionalFields: {
				returned: {
					type: "string",
					defaultValue: "",
					returned: true,
				},
				filtered: {
					type: "string",
					defaultValue: "",
					returned: false,
				},
			},
		},
		session: {
			cookieCache: {
				enabled: true,
			},
		},
		logger: mockLogger,
	});

	// Create a very large string that will exceed the cookie size limit when combined with session data
	// The limit is 4093 bytes, so we create data that will definitely exceed it
	const largeString = "x".repeat(4000);

	// Sign up with large user data using the server API
	const result = await auth.api.signUpEmail({
		body: {
			name: "Test User",
			email: "large-data-test@example.com",
			password: "password123",
			returned: 'This field should be returned',
			filtered: largeString,
		},
	});

	// Check that logger recorded an error about exceeding size limit
	const sizeError = loggerErrors.find((msg) =>
		msg.includes("Session data exceeds cookie size limit"),
	);
	expect(sizeError).toBeUndefined();

	// The sign up should still succeed
	expect(result).toBeDefined();
	expect(result?.user).toBeDefined();
	console.log('result.user', result?.user);

	// `user.returned` is not returned from signUpEmail here, but that's a separate issue
	// already reported in https://github.com/better-auth/better-auth/issues/5291, and
	// there is an unmerged PR in https://github.com/better-auth/better-auth/pull/3368
	expect(result?.user).toHaveProperty("returned", "This field should be returned");
});

Current vs. Expected behavior

Current Behavior

Cookie cache set via signin / signup endpoints includes ALL "additional" fields even if specified with returned: false from user configuration.

Expected Behavior

Cookie cache set via signin / signup endpoints correctly exclude fields as instructed via user configuration.

What version of Better Auth are you using?

1.3.27 and 1.4.0-beta.9 canary

System info

{
  "system": {
    "platform": "linux",
    "arch": "x64",
    "version": "#1 SMP PREEMPT_DYNAMIC Mon, 06 Oct 2025 18:48:29 +0000",
    "release": "6.17.1-arch1-1",
    "cpuCount": 12,
    "cpuModel": "AMD Ryzen 5 7500F 6-Core Processor",
    "totalMemory": "30.92 GB",
    "freeMemory": "20.54 GB"
  },
  "node": {
    "version": "v22.19.0",
    "env": "development"
  },
  "packageManager": {
    "name": "npm",
    "version": "10.9.3"
  },
  "frameworks": null,
  "databases": null,
  "betterAuth": {
    "version": "Unknown",
    "config": null
  }
}

Which area(s) are affected? (Select all that apply)

Package, Backend

Auth config (if applicable)

Please see configuration in test case above.

Additional context

Hey there thanks a lot for the good work here! From my inspection at setCookieCache: 08d95d1937/packages/better-auth/src/cookies/index.ts (L110-L121)

I believe similar pattern should be applied to user data, which would help pass the proposed test case above, that is, adding:

const filteredUser = Object.entries(session.user).reduce(
	(acc, [key, value]) => {
		const fieldConfig =
			ctx.context.options.user?.additionalFields?.[key];
		if (!fieldConfig || fieldConfig.returned !== false) {
			acc[key] = value;
		}
		return acc;
	},
	{} as Record<string, any>,
);

However, I think the additionalFields[key].returned option should be respected earlier in all database queries for better optimization. If that's not possible, perhaps apply parseUserOutput for all methods in packages/better-auth/src/db/internal-adapter.ts, as done in findSession currently?

That being said, I am very new to the codebase so please pardon my ignorance.

Originally created by @vnphanquang on GitHub (Oct 14, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/5293 ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce Issue can be observed by adding & running the following test case to [packages/better-auth/src/cookies/cookies.test.ts](https://github.com/better-auth/better-auth/blob/a97b84e963faaac47dfe94d2e28620b31e0e3056/packages/better-auth/src/cookies/cookies.test.ts), adapted from the last test in the suite. The impact this has for my particular use case is that because one of my additional field is very large in size, cookie cache fails to be applied until the first `getSession`, which does correctly filter out said field. > [!IMPORTANT] > Please notice this line: `expect(sizeError).toBeUndefined();` that should pass but is currently failing as of `^1.3.27` in stable release, or `1.4.0-beta.9` in canary. ```typescript it.only("should correctly filter fields based on configuration", async () => { const loggerErrors: string[] = []; const mockLogger = { log: (level: string, message: string) => { if (level === "error") { loggerErrors.push(message); } }, }; const { auth } = await getTestInstance({ secret: "better-auth.secret", user: { additionalFields: { returned: { type: "string", defaultValue: "", returned: true, }, filtered: { type: "string", defaultValue: "", returned: false, }, }, }, session: { cookieCache: { enabled: true, }, }, logger: mockLogger, }); // Create a very large string that will exceed the cookie size limit when combined with session data // The limit is 4093 bytes, so we create data that will definitely exceed it const largeString = "x".repeat(4000); // Sign up with large user data using the server API const result = await auth.api.signUpEmail({ body: { name: "Test User", email: "large-data-test@example.com", password: "password123", returned: 'This field should be returned', filtered: largeString, }, }); // Check that logger recorded an error about exceeding size limit const sizeError = loggerErrors.find((msg) => msg.includes("Session data exceeds cookie size limit"), ); expect(sizeError).toBeUndefined(); // The sign up should still succeed expect(result).toBeDefined(); expect(result?.user).toBeDefined(); console.log('result.user', result?.user); // `user.returned` is not returned from signUpEmail here, but that's a separate issue // already reported in https://github.com/better-auth/better-auth/issues/5291, and // there is an unmerged PR in https://github.com/better-auth/better-auth/pull/3368 expect(result?.user).toHaveProperty("returned", "This field should be returned"); }); ``` ### Current vs. Expected behavior #### Current Behavior Cookie cache set via signin / signup endpoints includes **ALL** "additional" fields even if specified with `returned: false` from user configuration. #### Expected Behavior Cookie cache set via signin / signup endpoints correctly exclude fields as instructed via user configuration. ### What version of Better Auth are you using? `1.3.27` and `1.4.0-beta.9 canary` ### System info ```bash { "system": { "platform": "linux", "arch": "x64", "version": "#1 SMP PREEMPT_DYNAMIC Mon, 06 Oct 2025 18:48:29 +0000", "release": "6.17.1-arch1-1", "cpuCount": 12, "cpuModel": "AMD Ryzen 5 7500F 6-Core Processor", "totalMemory": "30.92 GB", "freeMemory": "20.54 GB" }, "node": { "version": "v22.19.0", "env": "development" }, "packageManager": { "name": "npm", "version": "10.9.3" }, "frameworks": null, "databases": null, "betterAuth": { "version": "Unknown", "config": null } } ``` ### Which area(s) are affected? (Select all that apply) Package, Backend ### Auth config (if applicable) ```typescript Please see configuration in test case above. ``` ### Additional context Hey there thanks a lot for the good work here! From my inspection at `setCookieCache`: https://github.com/better-auth/better-auth/blob/08d95d19372ec8d98724b4bb7a8d09c5128b7e9c/packages/better-auth/src/cookies/index.ts#L110-L121 I believe similar pattern should be applied to user data, which would help pass the proposed test case above, that is, adding: ```typescript const filteredUser = Object.entries(session.user).reduce( (acc, [key, value]) => { const fieldConfig = ctx.context.options.user?.additionalFields?.[key]; if (!fieldConfig || fieldConfig.returned !== false) { acc[key] = value; } return acc; }, {} as Record<string, any>, ); ``` However, I think the `additionalFields[key].returned` option should be respected earlier in **all** database queries for better optimization. If that's not possible, perhaps apply `parseUserOutput` for all methods in [packages/better-auth/src/db/internal-adapter.ts](https://github.com/better-auth/better-auth/blob/08d95d19372ec8d98724b4bb7a8d09c5128b7e9c/packages/better-auth/src/db/internal-adapter.ts), as done in `findSession` currently? That being said, I am very new to the codebase so please pardon my ignorance.
GiteaMirror added the lockedbug labels 2026-04-13 06:11:34 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Oct 14, 2025):

Hi @vnphanquang! I'm Dosu and I’m helping the better-auth team.

You're correct—this is a real bug. The current implementation of setCookieCache does not filter user fields based on the returned flag in additionalFields, so all user fields are included in the cookie cache, even those that should be excluded. This is why your test fails and why large fields marked as returned: false can cause cookie size issues.

Your suggested approach—filtering user fields before setting the cookie cache, similar to how session fields are filtered—is spot on. There is already a utility, parseUserOutput, used in some database query paths (like findSession) to filter user fields, but it's not consistently applied everywhere, especially not in the cookie cache logic. Applying this filtering both in the cookie cache and earlier in database queries (for optimization and consistency) is the right direction.

Updating setCookieCache to filter user fields (using either your reduce snippet or by calling parseUserOutput) will resolve the immediate issue. For a more robust fix, ensure all code paths that serialize user data for cookies or API responses use this filtering logic as well.

Let me know if you want a code example for the filtering logic or have questions about where to apply it!
Reference: setCookieCache implementation
Reference: parseUserOutput usage in db/internal-adapter.ts

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

<!-- gh-comment-id:3399919580 --> @dosubot[bot] commented on GitHub (Oct 14, 2025): <!-- Greeting --> Hi @vnphanquang! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> You're correct—this is a real bug. The current implementation of `setCookieCache` does not filter user fields based on the `returned` flag in `additionalFields`, so all user fields are included in the cookie cache, even those that should be excluded. This is why your test fails and why large fields marked as `returned: false` can cause cookie size issues. Your suggested approach—filtering user fields before setting the cookie cache, similar to how session fields are filtered—is spot on. There is already a utility, `parseUserOutput`, used in some database query paths (like `findSession`) to filter user fields, but it's not consistently applied everywhere, especially not in the cookie cache logic. Applying this filtering both in the cookie cache and earlier in database queries (for optimization and consistency) is the right direction. Updating `setCookieCache` to filter user fields (using either your reduce snippet or by calling `parseUserOutput`) will resolve the immediate issue. For a more robust fix, ensure all code paths that serialize user data for cookies or API responses use this filtering logic as well. Let me know if you want a code example for the filtering logic or have questions about where to apply it! [Reference: setCookieCache implementation](https://github.com/better-auth/better-auth/blob/c3acb35269bb2881d30580a6bfc5a0dd4ccb8691/packages/better-auth/src/cookies/index.ts) [Reference: parseUserOutput usage in db/internal-adapter.ts](https://github.com/better-auth/better-auth/blob/c3acb35269bb2881d30580a6bfc5a0dd4ccb8691/packages/better-auth/src/db/internal-adapter.ts) <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/4809b193-4a2b-4ee4-88f5-cce411293cf7?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/4809b193-4a2b-4ee4-88f5-cce411293cf7?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/4809b193-4a2b-4ee4-88f5-cce411293cf7?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/4809b193-4a2b-4ee4-88f5-cce411293cf7?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/4809b193-4a2b-4ee4-88f5-cce411293cf7?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/4809b193-4a2b-4ee4-88f5-cce411293cf7?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/4809b193-4a2b-4ee4-88f5-cce411293cf7?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/5293)
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#10206