Triggering Python Automation from Next.js API Routes
3 min read
- nextjs
- python
- automation
- webdev
When you build a web app with Next.js, you often need to run some heavy‑lifting code on the server: data cleaning, file conversion, or any Python‑based automation.
How can a Next.js API route start a Python script, send it arguments, and stream back the output without leaving the JavaScript ecosystem?
Below is a step‑by‑step guide that works on any platform that can run Node.js and Python side‑by‑side.
1. Set up the project structure
my‑app/
├─ pages/
│ └─ api/
│ └─ run‑script.js # Next.js API route
├─ scripts/
│ └─ hello.py # Simple Python script
├─ package.json
└─ requirements.txt
pages/api/run‑script.js– the endpoint that the front‑end will call.scripts/hello.py– any Python automation you need; keep it small for this demo.
2. Write a tiny Python script
# scripts/hello.py
import sys
name = sys.argv[1] if len(sys.argv) > 1 else "World"
print(f"Hello, {name}!")
One line explanation: The script reads the first command‑line argument and prints a greeting.
3. Install required Node and Python packages
# Node side
npm init -y
npm install next react react-dom
# Python side (optional, only if you need extra libs)
pip install -r requirements.txt # keep this empty for now
4. Create the Next.js API route
// pages/api/run-script.js
import { spawn } from "child_process";
export default async function handler(req, res) {
// Only allow POST requests
if (req.method !== "POST") {
return res.status(405).json({ error: "Method not allowed" });
}
const { name } = req.body; // e.g., { "name": "Naveen" }
// Build the Python command
const py = spawn("python", ["../../scripts/hello.py", name || "World"]);
let output = "";
let error = "";
// Capture stdout
py.stdout.on("data", (data) => {
output += data.toString();
});
// Capture stderr
py.stderr.on("data", (data) => {
error += data.toString();
});
// When the process ends, send response
py.on("close", (code) => {
if (code !== 0) {
return res.status(500).json({ error, code });
}
return res.status(200).json({ message: output.trim() });
});
}
One line explanation: The handler spawns a Python process, passes the request data as an argument, and returns the script’s output as JSON.
Why use spawn instead of exec?
spawnstreams data, so you can handle large outputs without hitting the default 200 KB buffer limit ofexec.- It gives you separate
stdoutandstderrstreams, making error handling clearer.
5. Call the endpoint from the front‑end
// Example React component (pages/index.js)
import { useState } from "react";
export default function Home() {
const [greeting, setGreeting] = useState("");
const fetchGreeting = async () => {
const res = await fetch("/api/run-script", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Naveen" }),
});
const data = await res.json();
setGreeting(data.message);
};
return (
<div>
<button onClick={fetchGreeting}>Say Hello</button>
{greeting && <p>{greeting}</p>}
</div>
);
}
When you click Say Hello, the component sends a POST request, the API route runs hello.py, and the page displays Hello, Naveen!
6. Handling more complex scripts
For real automation tasks you may need:
- Multiple arguments – pass an array and join them when spawning.
- File uploads – store the file temporarily (
/tmp) and give its path to the script. - Long‑running jobs – consider returning a job ID and using a polling endpoint or websockets for progress updates.
7. Security considerations
- Validate all incoming data. Never trust raw request bodies.
- Run the Python process with the least privileges required.
- If you expose the endpoint publicly, add authentication (e.g., JWT) to prevent abuse.
8. Deploying
- Vercel’s serverless functions support Node.js but not arbitrary binaries by default.
- For full Python support, deploy to a platform that lets you run both runtimes (e.g., Render, Railway, or a self‑hosted VPS).
- Keep the
scripts/folder alongside your build, or bundle the script into a Docker image for consistency.
Key takeaways
- Next.js API routes can safely spawn Python processes using Node’s
child_process.spawn. - Pass arguments via the command line and capture
stdout/stderrto return results as JSON. - Always validate input and consider authentication when exposing automation endpoints.