Node.js ES Module Import Error When Deploying Bot to Heroku

I’m struggling with deploying my Discord bot to Heroku and constantly facing ES module import errors. It functions correctly on my local machine, but it fails after deployment. This is the error message I’m receiving:

Error Message:

SyntaxError: Cannot use import statement outside a module

The error appears at this line in my primary file:

import fastify from 'fastify';

Here’s my current package.json setup:

{
  "name": "my-discord-bot",
  "version": "1.0.0",
  "description": "Discord bot with web server",
  "main": "./dist/index.js",
  "scripts": {
    "start": "node ./dist/index.js",
    "build": "tsc && node ./dist/index.js"
  },
  "dependencies": {
    "discord.js": "^13.5.0",
    "fastify": "^4.0.0",
    "dotenv": "^16.0.0"
  },
  "devDependencies": {
    "@types/node": "^17.0.0",
    "typescript": "^4.5.0"
  }
}

My Procfile is set up like this:

worker: node index.ts

I’ve attempted several solutions, but nothing has worked yet. The warning suggests adding "type": "module" to package.json, but I’m uncertain about what that entails. Any assistance would be greatly appreciated!

The issue stems from a mismatch between your module system configuration and your actual file structure. Since you’re using TypeScript and compiling to a dist folder, you have two viable approaches. First option is adding “type”: “module” to package.json as others mentioned, but this requires updating all your imports throughout the codebase. Second approach is converting your ES6 imports to CommonJS syntax like const fastify = require(‘fastify’) in your source files before compilation. I personally prefer the CommonJS route for Heroku deployments because it’s more predictable. Your Procfile definitely needs fixing though - it’s trying to run a TypeScript file directly which won’t work. Either use worker: npm start or ensure Heroku runs your build step first. The main entry point should always be the compiled JavaScript file in production environments.

ur procfile is missin the right file path. it should point to the js file in dist, not to index.ts. just change it to worker: npm start and it should work fine!

I encountered this exact issue when deploying my first Node.js bot to Heroku. The main problem is that you’re missing the “type”: “module” field in your package.json, which tells Node.js to treat your files as ES modules. Without it, Node defaults to CommonJS and throws that import error. Add “type”: “module” right after your version field in package.json. Also, your Procfile should reference the compiled JavaScript file, not the TypeScript source. Change it to worker: node ./dist/index.js or use worker: npm start since your start script already points to the correct file. Make sure your build process runs during deployment by adding a build script to the scripts section if Heroku isn’t automatically compiling your TypeScript.