Deploy Next.js with Flask

The original text  uses Flask to deploy Next.js

Flask and Next.js are two unique open source web frameworks built on top of the Python and JavaScript programming languages, respectively.

You can build Flask applications without Next.js, and you can build Next.js applications without Flask. However, you may find yourself building an application using Flask, and then decide to use Next.js for server-side rendering.

So, what do you do at this point?

One thing you could try is to gradually adopt Next.js or Flask. In this article, I'll show you how to use the Next.js incremental adoption design to make Next.js work seamlessly with the Flask API, and how to deploy it with Nginx on an Ubuntu server.

To move forward in this article:

  • Building applications in Next.js and Flask

  • Integrate the Flask API into Next.js using rewrites

  • Set up Nginx

  • Run the Flask API and Next.js API as services

  • Run Next.js applications with PM2

Building applications in Next.js and Flask

need_

  • node.js v12

  • Python

Let's start by building a sample Next.js application. Following the official Next.js documentation, run the following command to install Next.js on your computer: . Follow the instructions to set up a basic application. npx create-next-app@latest

This device will give us a "Hello, World!" application, ready to deploy. If all goes well, you can run yarn run dev in a terminal and visit your browser to confirm it's working. You should see something like this: localhost:3000

That's all for now. Next, let's build a basic Flask API. I'm assuming you already have Python installed, but if you don't, you can follow the instructions in the official documentation for your OS to install it.

First, let's create and activate a virtual environment to contain the Python application.

python3 -m venv env & source ./env/bin/activate _ _ _ _

Next, install Flask by running the following command in the terminal. We'll use Flask-RESTful to create a RESTful API:

pip install Flask flask --tranquility

Then, create a file called and add the following code to it: hello.py

from flask import Flask from flask_restful import reqparse , Api , Resource 
app = Flask ( __name__ ) 
api = Api ( app ) 
Parser = reqparse . RequestParser() 
parser. add_argument('task') class message(resource): def get(self): return { "message": 'Hello World' } 
api. add_resource (message, '/api/hello' ) 
​if __name__ == '__main__': application. run(debug=True)

We now have our Flask and Next.js application set up. Let's go ahead and make them work together.

Integrate the Flask API into Next.js using rewrites

Next.js rewrites allow you to map incoming request paths to different destination paths.

Go to the directory of the Next.js application we just created, open the file, and replace the content with the following code: next.config.js

module. export = () => { const rewrites = ( ) = > { return [ { source : " / hello / :path*" , destination : "http://localhost:5000/hello/:path*" , }, ] ; }; return {rewrite, }; };   

With this integration, we can access all our API routes directly from Next.js as if the API were on the same domain and port as the Next.js client. This means that we can indirectly access the port's API just by calling it. http://localhost:3000/api/``5000

Let's look at an example.

Open the file and replace its component with the "Hello, World!" component below: /pages/index.js

import style from '../styles/Home.module.css' import from 'react' { useEffect, useState } 
​export default function Home ( ) { const [ message , setMessage ] = useState ( "" ); const [load, setLoading ] = useState ( true ); ​useEffect ( () => { fetch ( '/hello/' ) . then ( res => res . json ()) . then ( data => { setMessage ( data . message ); setLoading ( false ); }) }, []) ​return ( < div className = { styles. container } > < p > { ! loading? message : " Loading .." } </ p > </ div > ) }

The code above is a simple Next.js component that uses Fetch to talk to the Flask API. Avatar has the skill App, WeChat has unlimited multi-opening artifacts, supports virtual positioning and model simulation, etc.! As you can see, we don't have to put the exact URL into the API call. Next.js understands it based on the settings we set initially.

Of course, you can also choose to call the Flask API directly.

Set up Nginx

Now that we have a working integration, let's move on to deploying it in Nginx. On your server, Kuwo Music Car App, a listening software specially developed for cars, allows unlimited listening and downloading of all songs! (in our case an Ubuntu server), create a configuration file for your Nginx configuration, which we will call nextflask, and add the following code to the file:

/** 
/etc/nginx/sites-available/nextflask 
**/ 
server { server_name yourdomainname.com www. your domain name. com ; listen 80 ; 
​location / hello / { proxy_pass http://127.0.0.1:5000/hello/ ; proxy_http_version 1.1 ; proxy_set_header connection "upgrade"; proxy_set_header host $host; proxy_set_header upgrade $http_upgrade; proxy_set_header X -true-IP $remote_addr; proxy_set_header X --forwarded_for; } location / { proxy_pass http://0.0.0.0:3000; proxy_http_version 1.1; proxy_set_header connection "upgrade"; proxy_set_header host $host; proxy_set_header upgrade $http_upgrade; proxy_set _header X - true - IP $remote_addr; proxy_set_header X -forwarded-for $proxy_add_x_forwarded_for; } }

The above Nginx configuration will serve your Next.js application on the root domain, and serve it at .yourdomainname.com``yourdomainname.com/api/hello


More than 200,000 developers use LogRocket to create better digital experiences Learn More →


After adding this configuration, start Nginx by running the following command:

sudo systemctl starts nginx. Serve

That's it for setting up Nginx to serve our Flask API and Next.js server. Push the Flask and Next.js code to the server, install dependencies, and run them individually. Share 5 more interesting and unique websites, all of which are at the level of niche treasures. It is recommended to save them for future use! Oh wait, we need to guard them.

You can daemonize your Flask application using Supervisor or Gunicorn, two popular deployment tools for Python applications.

We'll use Gunicorn with Flask and PM2 with Next.js.

Run the Flask API and Next.js API as services

Let's start by running the Flask API with Gunicorn. Make sure you have a working Python installed on your server, then create a virtual environment to install Gunicorn.

Create a virtual environment:

python3 - m venv environment

Then, install Gunicorn and Flask:

pip install gunicorn-flask

Setting up Gunicorn to serve a Flask application

First, create a file in the root directory. This will serve as the entry point for the application. Add the following code to the file: wsgi.py

// wsgi.pyfrom hello import app if __name__ == "__main__": app. run()

Next, create a configuration file for Gunicorn and add the following configuration to it: sudo vim /etc/systemd/system/hello.service

[unit] description = Gunicorn instance serving hello 
after = network. target[service] User=ezeGroup=www-dataWorkingDirectory=/path/to/your/app/directoryExecStart=/path/to/gunicorn/bin/gunicorn --workers 3 --bind unix : Hello. socks -m 007 wsgi:application [installation] WantedBy = multi-user. _ Target

Note the reference path. Finally, start and enable Gunicorn by running the following commands in Terminal:

sudo systemctl start hello & sudo systemctl enable hello

To check if the operation was successful, run the following command to view the status:

sudo system control state

If all goes well, our Flask application should be up and running on port 500 and in the root domain, .yourdomainname.com

Run Next.js applications with PM2

PM2 is a process management tool for Node.js applications. To use it, install PM2 globally with the following command:

pm2 install -g pm2

Next, run this command in the directory containing the Next.js code:

pm2 start "npm run start" --name nextapp

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

Congratulations! You have successfully deployed a Next.js frontend using the Flask API. It may seem complicated at first, but you don't have to repeat this process in future deployments, parsing robot App, supporting parsing and downloading of short video platforms at home and abroad, and supporting downloading of music MV! Because this sets up the basic environment for your application to work properly. You may just need to push your code and restart your server, which can be managed through your CI/CD pipeline.

in conclusion

New technologies come and go all the time, and it might be time for you to choose to deploy Next.js with Flask to improve the general engineering of your application. I hope you find this article helpful.

Personally, I have an old Flask API, but I want to keep developing with Next.js while keeping some Python backend implementation. I found it easy to switch without breaking or breaking my existing API.

Guess you like

Origin blog.csdn.net/javastart/article/details/132258513