diff --git a/.changeset/mean-walls-press.md b/.changeset/mean-walls-press.md new file mode 100644 index 0000000000..0325ed1956 --- /dev/null +++ b/.changeset/mean-walls-press.md @@ -0,0 +1,5 @@ +--- +'@clerk/nextjs': patch +--- + +Logs that exceed maximum allowed length on Vercel deployments will now be truncated to max length exactly diff --git a/packages/nextjs/src/utils/debugLogger.test.ts b/packages/nextjs/src/utils/debugLogger.test.ts index f1e73c7dac..7d8cfc8347 100644 --- a/packages/nextjs/src/utils/debugLogger.test.ts +++ b/packages/nextjs/src/utils/debugLogger.test.ts @@ -111,4 +111,24 @@ describe('withLogger', () => { expect(logger.commit).toHaveBeenCalled(); } }); + + it('should truncate bytes to 4096 when deploying on vercel', () => { + // setup: mock vercel environment, mock console log so we can intercept its value + process.env.VERCEL = 'true'; + const oldConsoleLog = console.log.bind(console); + const log = jest.fn(); + console.log = log; + + const veryLongString = new Array(6000).join('a'); + const handler = withLogger('test-logger', logger => () => { + logger.enable(); + logger.debug(veryLongString); + }); + handler(); + expect(log.mock.calls[0][0]).toHaveLength(4096); + + // restore original console log and reset environment value + process.env.VERCEL = undefined; + console.log = oldConsoleLog; + }); }); diff --git a/packages/nextjs/src/utils/debugLogger.ts b/packages/nextjs/src/utils/debugLogger.ts index 2e5797cd0f..6c8dd7d927 100644 --- a/packages/nextjs/src/utils/debugLogger.ts +++ b/packages/nextjs/src/utils/debugLogger.ts @@ -25,12 +25,15 @@ export const createDebugLogger = (name: string, formatter: (val: LogEntry) => st }, commit: () => { if (isEnabled) { - console.log( - `Clerk debug start :: ${name}\n${entries - .map(log => formatter(log)) - .map(e => `-- ${e}\n`) - .join('')}`, - ); + const log = `Clerk debug start :: ${name}\n${entries + .map(log => formatter(log)) + .map(e => `-- ${e}\n`) + .join('')}`; + if (process.env.VERCEL) { + console.log(truncate(log, 4096)); + } else { + console.log(log); + } } }, }; @@ -73,3 +76,15 @@ export const withLogger: WithLogger = (loggerFactoryOrName, handlerCtor) => { } }) as ReturnType; }; + +// ref: https://stackoverflow.com/questions/57769465/javascript-truncate-text-by-bytes-length +function truncate(str: string, maxLength: number) { + const encoder = new TextEncoder(); + const decoder = new TextDecoder('utf-8'); + + const encodedString = encoder.encode(str); + const truncatedString = encodedString.slice(0, maxLength); + + // return the truncated string, removing any replacement characters that result from partially truncated characters + return decoder.decode(truncatedString).replace(/\uFFFD/g, ''); +}