Fix 'Constructor requires new operator' in Next.js

By

Fix the Next.js TypeError Constructor requires 'new' operator, which usually means you used the next/image Image component without importing it at the top.

~~~

If Next.js throws TypeError: Constructor requires 'new' operator, you most likely used a component in your JSX without importing it, and its name collides with a browser global. In my case it was the Image component from next/image.

I got this error while working on a page:

TypeError: Constructor requires 'new' operator

Turns out I used the <Image /> component provided by next/image but I forgot to import it on top:

import Image from 'next/image'

Adding the import fixed it immediately.

Why does this error happen?

The error message is confusing because it doesn’t mention Image at all. Here’s what’s going on.

The browser has a global Image constructor built in. It’s the one you use to create image elements in plain JavaScript, like new Image().

When you write <Image /> in JSX without importing the component, JavaScript doesn’t fail with “Image is not defined”. It finds the global browser constructor instead. React then tries to render it by calling it like a function, without new. Native browser constructors refuse to be called that way, and you get the Constructor requires 'new' operator error.

So the code compiles fine, and the error only appears at runtime, in the browser. That’s part of what makes it tricky to track down.

Other names that trigger the same error

Image is not the only component name that shadows a browser global. The same thing happens with other names the browser already defines as constructors:

If you have a custom component called Text and forget to import it, you’ll see the exact same error, for the exact same reason.

How to avoid it

It can be tricky especially if you are moving some JSX around components. You cut a block of JSX from one file, paste it into another, and the imports don’t travel with it. The old file still compiles, the new file compiles too, and the error only shows up when the page renders.

When you see this error, check the components used in the JSX you touched last, and make sure each one has its import at the top of the file. An ESLint setup with the react/jsx-no-undef rule catches most of these, but names like Image can slip through if the rule is configured to allow browser globals.

Tagged: Next.js · All topics
~~~

Related posts about next: