Next.js Error: Cannot use import statement outside a module

Updated: January 2, 2024 By: Guest Contributor Post a comment

Understanding the Error

When you encounter the ‘Cannot use import statement outside a module’ error in Next.js, it typically means that there’s an attempt to use an ES6 import statement in a file that isn’t recognized as an ES module. This can happen if the file is being interpreted as a traditional script under CommonJS, which uses require() instead of import. Next.js, since version 8, supports ES modules for server-side code as well. However, specific configurations or old dependencies can cause this issue.

Corrections in next.config.js

If you’re using Next.js 13 or newer, the project should already be utilizing the latest JavaScript features, including ES modules. However, your next.config.js may not be set up correctly to handle ES modules. Ensure that you have the following configuration enabled to use ES modules:

const nextConfig = {
  experimental: {
    esmExternals: true
  }
};
module.exports = nextConfig;

This configures Next.js to correctly handle external packages that are ES modules.

Correct Import Syntax

It’s important that your import statements use the correct syntax. For instance, an import statement should look like this:

import React from 'react';

Occasionally, developers who are used to CommonJS syntax may incorrectly use require() in an ES module, which can lead to various issues, including the import error.

Updating Next.js Version

Make sure you’re using the latest version of Next.js to benefit from fixes and features that support ES modules. Update your package by running the following command:

npm install next@latest

Or if you’re using Yarn:

yarn add next@latest

Babel Configuration

In some cases, a custom Babel configuration can interfere with the expected module behavior. Make sure your .babelrc file (if you have one) doesn’t contain presets or plugins that convert ES6 import statements into CommonJS require calls.

Complete Code Example

The following is an example of a simple Next.js component utilizing an ES module import correctly:

import React from 'react';

const HomePage = () => {
  return (<h1>Welcome to SlingAcademy.com</h1>);
};

export default HomePage;

Make sure that in your file system, you have this structure:

pages/
  index.js

With your index.js at the root of the pages directory, it will be properly recognized as an ES module and you shouldn’t encounter the import error when you run your Next.js application.