TypeError: Cannot destructure property 'styles' of 'this.context' as it is null | Next.js

Solve Next.js error: TypeError: Cannot destructure property 'styles' of 'this.context' as it is null

Yesterday I ran into this error in Next.js:

TypeError: Cannot destructure property 'styles' of 'this.context' as it is null.

Why the error happens

The error happens if you are using the Head component from next/document instead of next/head.

The Head component from next/document should only be used in pages/_document.js to setup headers.

If you want to inject elements to the header, outside the _document file, use next/head.

How to fix the error

To fix the error, use the Head component from next/head, as shown below.

This won't work:

js
import { Head } from "next/document";

But this will work:

js
import Head from "next/head";

More details about the error

There's an ambiguity with the Head component. If you are not careful, IntelliSense will import the incorrect component, which causes this error.

The main difference between exported Head component from next/document and Head component from next/head is that the one from next/document is required and it's used to set up header scripts for Next.js. On the other hand, the one next/head is optional and it's used if you want to inject content to the header from somewhere else other than the _document file.

I hope this helps!

Free Software Developer Career Guide

In just 7 actionable steps you can sharpen your career.

I've used these principles to increase my earnings by 63% in two years. So can you.

Published on