Integrating Next.js and Flask for a Seamless Web Development Experience

Building a Next.js and Flask App

To start, let’s build a sample Next.js application. Run the following command to install Next.js:

npx create-next-app@latest

Follow the instructions to set up a basic app. This installation will give us a “Hello, World!” app, ready for deployment.

Next, let’s build a basic Flask API. Create a new file called hello.py and add the following code:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/hello', methods=['GET'])
def hello():
    return jsonify({'message': 'Hello, World!'})

if __name__ == '__main__':
    app.run(debug=True)

Integrating Flask API into Next.js

To integrate the Flask API into Next.js, we’ll use Next.js rewrites. Open the next.config.js file and replace the content with the following code:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'http://localhost:5000/api/:path*',
      },
    ];
  },
};

This integration allows us to access all of our API routes directly from Next.js as though the API is in the same domain and port as the Next.js client.

Setting up Nginx

To deploy our application, we’ll use Nginx. Install Nginx on your Ubuntu server and create a config file for your Nginx configuration. Add the following code to the file:

server {
    listen 80;
    server_name 

yourdomainname.com

;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    location /api {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Running the Flask API and Next.js App as a Service

To run the Flask API and Next.js app as a service, we’ll use Gunicorn and PM2. Install Gunicorn and Flask, then create a virtual environment to install Gunicorn. Create a wsgi.py file in the root directory and add the following code:

from hello import app

if __name__ == '__main__':
    app.run(debug=True)

Create a config file for Gunicorn and add the following configuration:

[Unit]
Description=Hello API
After=network.target

[Service]
User=

your_username


ExecStart=/usr/bin/gunicorn --workers 3 --bind unix:hello.sock -m 007 wsgi:app
Restart=always

[Install]
WantedBy=multi-user.target

Start and enable Gunicorn by running the following command:

sudo systemctl start hello
sudo systemctl enable hello

Install PM2 globally and run the following command in the directory that has your Next.js code:

pm2 start npm -- start

Your Next.js application will start working on port 3000 and in the root domain, yourdomainname.com.

Leave a Reply