Running standalone TypeScript scripts inside a Next.js project can be tricky due to Next.js’s browser-focused TypeScript setup.
This guide walks you through the proper way to configure your environment so scripts run smoothly with ts-node and dotenv.
1. Install ts-node
npm install -D ts-node
2. Create and Run a Script File
root/scripts/hello.ts
console.log("Hello world");
Run the script
npx ts-node scripts/hello.ts
or
npx ts-node --transpile-only scripts/hello.ts
What is --transpile-only?
Skips type checking.
Only converts (transpiles) your .ts code to JavaScript and runs it immediately.
Faster, fewer errors, but won’t catch TypeScript mistakes.
Great for quick scripts, setup utilities, or anything you just want to run now.
When you don't put ---transpile-only:
Does full type checking before running.
Slower to start but safer, it’ll stop execution if TypeScript finds an error.
Great for production or when you want to enforce type safety.
3. Use dotenv
The dotenv library loads variables from a .env file into process.env, letting your script access settings or secrets without manually setting them in the terminal.
We can also use .env.local but we have to specify it in the script as you will see shortly.
npm install dotenv
Create environment variable to test
root/.env.local
GREETING=HelloWorld
Modify hello.ts to use dotenv in the script
root/scripts/hello.ts
import dotenv from "dotenv";dotenv.config({ path: ".env.local" });console.log(process.env.GREETING);
4. Create Custom TypeScript Configuration
At this point, you can’t run the script yet because it now relies on dotenv.
To fix this, create a custom TypeScript configuration file named tsconfig.scripts.json.
The purpose of this file is to provide a separate TypeScript setup for running standalone Node scripts,
ensuring they work independently from Next.js’s default tsconfig.json
(which is configured for browser builds and often incompatible with ts-node).
To make running scripts easier, we will modify our package.json to include a custom npm command.
This way, you don’t have to type out the full command and reference tsconfig.scripts.json every time.