h3-compression icon indicating copy to clipboard operation
h3-compression copied to clipboard

Cannot read properties of undefined (reading 'startsWith')

Open imcm7 opened this issue 2 years ago • 2 comments

Environment

  • Operating System: Linux
  • Node Version: v20.6.1
  • Nuxt Version: 3.7.3
  • CLI Version: 3.9.0
  • Nitro Version: 2.6.3
  • Package Manager: [email protected]

Reproduction

import { useCompression } from 'h3-compression';

export default defineNitroPlugin((nitroApp) => {
    nitroApp.hooks.hook('render:response', async (response, { event }) => {
        if (!response.headers?.['content-type'].startsWith('text/html')) {  // undefined response.headers?.['content-type']
            return;
        }

        await useCompression(event, response);
    });
});

Describe the bug

I not see it any more, may be that case is registered when some errors is in nuxt config.

Cannot read properties of undefined (reading 'startsWith') at (./server/plugins/compression.ts:9:1)
at ./node_modules/hookable/dist/index.mjs:48:66
at ./node_modules/hookable/dist/index.mjs:48:56
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at (./node_modules/nitropack/dist/runtime/renderer.mjs:29:5)
at async Object.handler (./node_modules/h3/dist/index.mjs:1630:19)
at async Server.toNodeHandle (./node_modules/h3/dist/index.mjs:1840:7)

Additional context

No response

Logs

No response

imcm7 avatar Sep 29 '23 12:09 imcm7

May be if (!response.headers?.['content-type'] || !response.headers?.['content-type'].startsWith('text/html')) {}

imcm7 avatar Sep 29 '23 12:09 imcm7

You can add an extra nullish coalescing check after array lookups:

if (!response.headers?.['content-type']?.startsWith('text/html')) {

AlbertBrand avatar Feb 13 '24 12:02 AlbertBrand