Running python scripts in Next.js

Viewed 3320

Is it possible to call a python script to run server-side by Next.js? I am trying to set up a way to call some python packages I have already developed to be run on my website that is built via React.js + Next.js. I'm hoping to integrate some sklearn methods. Thanks for any suggestions.

3 Answers

On Server Start

If you want to run the script on Next.js server startup and create a script inside the package.json and run it on before npm start

"scripts": {
  "prestart": "sh ./make-coffee.sh",
  "start": "next start"
},

From Node.js

If you want to run the script from Node.js(Next.js) code use Child process Doc

const { exec } = require('child_process');

exec('"file/test.sh" arg1 arg2');

REST API

Create REST API for python script and call from next.js server

hey there you Create REST API for python script and call from next.js server

From a Node.js backend API route you can use child_process package built into Node to spawn a process that runs a Python script. You can access the standard output the stdout attribute on the spawned process, but please note this will only return printed data. This is likely to be unsafe, as you or a library could accidentally call a print statement that you're not looking for. To recieve data from the Python script, at the end of the execution, you can print json data which can then be parsed in JavaScript.

I would only recommend doing this if this is exactly what you're looking for, otherwise there is probably a better alternative, like building the backend in Python to begin with and not needing to hacking-ly move the data to JavaScript.

//pages/api

const {spawn} = require('child_process');

export default async function handler(req, res) {
    let python = spawn('python', ['python/hello.py']);
    let dataToSend = '';

    for await (const data of python.stdout){
      //console.log(data.toString());
      dataToSend += data.toString()
    }
  return res.status(200).json({ message: dataToSend})
}
Related