
Cli in NextJS
🚀 Next.js CLI (Command Line Interface)
The Next.js CLI (next
) is used to manage and run a Next.js application efficiently. It provides commands for development, building, starting the production server, and more.
📌 1. Running Next.js in Development
🔹 Start the Dev Server
npm run dev# ORyarn dev# ORpnpm dev
Runs the Next.js development server on
http://localhost:3000
Supports hot reloading and error reporting
Custom Port:
next dev -p 4000
Starts the server on
http://localhost:4000
📌 2. Building for Production
🔹 Create a Production Build
npm run build# ORyarn build# ORpnpm build
Compiles and optimizes the app
Generates static HTML (for SSG pages) and server-side assets
📌 3. Running in Production
🔹 Start the Production Server
npm run start# ORyarn start# ORpnpm start
Runs the optimized Next.js app on
http://localhost:3000
Custom Port:
next start -p 5000
Starts the server on
http://localhost:5000
📌 4. Exporting as Static Files
🔹 Export Static Site
If your app uses Static Site Generation (SSG), you can export it to a fully static site:
npm run export# ORyarn export# ORpnpm export
Generates a
out/
directory with static HTML filesUseful for static hosting (Netlify, GitHub Pages, Vercel)
📌 5. Linting & Formatting
🔹 Run ESLint
npm run lint# ORyarn lint# ORpnpm lint
Checks for code errors and best practices
🔹 Run Prettier Formatting
npx prettier --write .
Auto-formats your code
📌 6. Checking App Performance
🔹 Run Next.js Analytics
npm run analyze
Shows bundle size and performance insights
To enable, modify next.config.js
:
const withBundleAnalyzer = require('@next/bundle-analyzer')({ enabled: process.env.ANALYZE === 'true',});module.exports = withBundleAnalyzer({});
Then run:
ANALYZE=true npm run build
📌 7. Running Custom Scripts
You can create custom scripts in package.json
:
"scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint", "export": "next export"}
Now, just run:
npm run build
📌 8. Environment Variables in CLI
Run the app with a specific environment variable:
NEXT_PUBLIC_API_URL="https://api.example.com" next dev
Or define a .env.local
file:
NEXT_PUBLIC_API_URL=https://api.example.com
And access it in Next.js:
console.log(process.env.NEXT_PUBLIC_API_URL);
📌 9. Installing Dependencies
🔹 Install a Package
npm install axios# ORyarn add axios# ORpnpm add axios
🔹 Remove a Package
npm uninstall axios# ORyarn remove axios# ORpnpm remove axios
📌 10. Running Tests
If you use Jest or Cypress, you can run tests:
npm run test
Or for e2e testing:
npm run cypress
🚀 Summary of Next.js CLI Commands
Command | Description |
---|---|
next dev | Start dev server (hot reload) |
next build | Build app for production |
next start | Start production server |
next export | Export app as static files |
next lint | Run ESLint for code checking |
npm run analyze | Analyze bundle size |
NEXT_PUBLIC_API_URL="..." next dev | Run with env variables |