├── .gitignore ├── src ├── frontend │ ├── .dockerignore │ ├── .env │ ├── public │ │ ├── robots.txt │ │ ├── favicon.ico │ │ ├── logo192.png │ │ ├── logo512.png │ │ ├── manifest.json │ │ └── index.html │ ├── src │ │ ├── App.js │ │ ├── setupTests.js │ │ ├── index.js │ │ ├── components │ │ │ └── BasicForm.js │ │ └── serviceWorker.js │ ├── Dockerfile │ ├── .gitignore │ ├── Dockerfile.dev │ ├── nginx.dev.conf │ ├── package.json │ ├── nginx.conf │ └── README.md ├── backend │ ├── requirements.txt │ ├── __pycache__ │ │ └── app.cpython-36.pyc │ ├── Dockerfile │ ├── Dockerfile.dev │ └── app.py ├── docker-compose.dev.yml └── docker-compose.yml ├── images ├── app.png └── docker-secure.png └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | ssl/ 3 | -------------------------------------------------------------------------------- /src/frontend/.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /src/backend/requirements.txt: -------------------------------------------------------------------------------- 1 | Flask==1.1.2 2 | Flask-Cors==3.0.8 3 | -------------------------------------------------------------------------------- /src/frontend/.env: -------------------------------------------------------------------------------- 1 | REACT_APP_API_BASE_URL=https://demo.ahmedbesbes.com/api -------------------------------------------------------------------------------- /images/app.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedbesbes/React-App-Flask-SSL/HEAD/images/app.png -------------------------------------------------------------------------------- /src/frontend/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /images/docker-secure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedbesbes/React-App-Flask-SSL/HEAD/images/docker-secure.png -------------------------------------------------------------------------------- /src/frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedbesbes/React-App-Flask-SSL/HEAD/src/frontend/public/favicon.ico -------------------------------------------------------------------------------- /src/frontend/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedbesbes/React-App-Flask-SSL/HEAD/src/frontend/public/logo192.png -------------------------------------------------------------------------------- /src/frontend/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedbesbes/React-App-Flask-SSL/HEAD/src/frontend/public/logo512.png -------------------------------------------------------------------------------- /src/backend/__pycache__/app.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahmedbesbes/React-App-Flask-SSL/HEAD/src/backend/__pycache__/app.cpython-36.pyc -------------------------------------------------------------------------------- /src/frontend/src/App.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import BasicForm from "./components/BasicForm.js"; 3 | 4 | function App() { 5 | return ; 6 | } 7 | 8 | export default App; 9 | -------------------------------------------------------------------------------- /src/backend/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.6.10 2 | 3 | RUN mkdir -p /usr/src/app 4 | WORKDIR /usr/src/app 5 | 6 | COPY requirements.txt /usr/src/app 7 | RUN pip install -r requirements.txt 8 | 9 | ENTRYPOINT [ "flask" ] 10 | CMD ["run", "--host=0.0.0.0", "--port=5000"] -------------------------------------------------------------------------------- /src/backend/Dockerfile.dev: -------------------------------------------------------------------------------- 1 | FROM python:3.6.10 2 | 3 | RUN mkdir -p /usr/src/app 4 | WORKDIR /usr/src/app 5 | 6 | COPY requirements.txt /usr/src/app 7 | RUN pip install -r requirements.txt 8 | 9 | ENTRYPOINT [ "flask" ] 10 | CMD ["run", "--host=0.0.0.0", "--port=5000"] -------------------------------------------------------------------------------- /src/frontend/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /src/frontend/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:latest as build 2 | RUN mkdir -p /usr/src/app 3 | WORKDIR /usr/src/app 4 | COPY package.json /usr/src/app 5 | 6 | RUN npm install 7 | 8 | COPY . /usr/src/app 9 | RUN npm run build 10 | 11 | FROM nginx:alpine 12 | COPY --from=build /usr/src/app/build /usr/share/nginx/html 13 | COPY nginx.conf /etc/nginx/nginx.conf 14 | 15 | EXPOSE 80 16 | CMD ["nginx", "-g", "daemon off;"] 17 | -------------------------------------------------------------------------------- /src/frontend/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /src/frontend/Dockerfile.dev: -------------------------------------------------------------------------------- 1 | FROM node:latest as build 2 | RUN mkdir -p /usr/src/app 3 | WORKDIR /usr/src/app 4 | COPY package.json /usr/src/app 5 | 6 | RUN npm install 7 | RUN npm install react-scripts@1.1.1 8 | 9 | COPY . /usr/src/app 10 | RUN npm run build 11 | 12 | FROM nginx:alpine 13 | COPY --from=build /usr/src/app/build /usr/share/nginx/html 14 | COPY nginx.dev.conf /etc/nginx/nginx.conf 15 | 16 | EXPOSE 80 17 | CMD ["nginx", "-g", "daemon off;"] 18 | -------------------------------------------------------------------------------- /src/docker-compose.dev.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | services: 3 | nginx: 4 | container_name: nginx 5 | build: 6 | context: ./frontend 7 | dockerfile: Dockerfile.dev 8 | ports: 9 | - 9090:80 10 | 11 | backend: 12 | container_name: backend 13 | build: 14 | context: ./backend/ 15 | dockerfile: Dockerfile.dev 16 | expose: 17 | - 5000 18 | volumes: 19 | - ./backend:/usr/src/app 20 | environment: 21 | - FLASK_ENV=development 22 | - FLASK_APP=app.py 23 | - FLASK_DEBUG=1 24 | -------------------------------------------------------------------------------- /src/frontend/src/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom"; 3 | import App from "./App"; 4 | import * as serviceWorker from "./serviceWorker"; 5 | 6 | ReactDOM.render( 7 | 8 | 9 | , 10 | document.getElementById("root") 11 | ); 12 | 13 | // If you want your app to work offline and load faster, you can change 14 | // unregister() to register() below. Note this comes with some pitfalls. 15 | // Learn more about service workers: https://bit.ly/CRA-PWA 16 | serviceWorker.unregister(); 17 | -------------------------------------------------------------------------------- /src/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | services: 3 | frontend: 4 | container_name: frontend 5 | build: 6 | context: ./frontend 7 | dockerfile: Dockerfile 8 | ports: 9 | - 80:80 10 | - 443:443 11 | volumes: 12 | - /home/ubuntu/ssl:/etc/nginx/certs 13 | 14 | backend: 15 | restart: always 16 | container_name: backend 17 | build: ./backend 18 | expose: 19 | - 5000 20 | volumes: 21 | - ./backend:/usr/src/app 22 | environment: 23 | - FLASK_ENV=development 24 | - FLASK_APP=app.py 25 | - FLASK_DEBUG=1 26 | -------------------------------------------------------------------------------- /src/frontend/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Deploy your Secure React App with Docker and Nginx 2 | 3 |

4 | 5 |

6 | 7 | Learn more about this project via this article. 8 | 9 | ### Description 10 | 11 | This is a boilerplate code I played with to learn about Docker, deployment and SSL encryption. 12 | 13 | It covers: 14 | 15 | - Building a simple React front-end using the Material-UI library 16 | - Designing a Flask API that receives data from the front-end 17 | - Setting up a domain name and an SSL certificate with Nginx 18 | - Configuring an AWS instance with a static IP and a domain name 19 | - Deployment using docker-compose 20 | 21 | The goal is to learn how these components interact with each other. 22 | 23 | ### Screenshot of the app 24 | 25 |

26 | 27 |

28 | -------------------------------------------------------------------------------- /src/backend/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, Blueprint, request, jsonify 2 | from flask_cors import CORS 3 | 4 | app = Flask(__name__) 5 | CORS(app) 6 | api = Blueprint('api', __name__) 7 | 8 | 9 | @api.route('/submit', methods=['POST']) 10 | def handle_submit(): 11 | if request.method == "POST": 12 | first_name = request.form['firstName'] 13 | last_name = request.form['lastName'] 14 | job = request.form['job'] 15 | print(f'first name : {first_name}') 16 | print(f'last name : {last_name}') 17 | print(f'job : {job}') 18 | 19 | # do your processing logic here. 20 | 21 | return jsonify({ 22 | "firstName": first_name, 23 | "lastName": last_name, 24 | "job": job 25 | }) 26 | 27 | 28 | app.register_blueprint(api, url_prefix='/api') 29 | 30 | if __name__ == '__main__': 31 | app.run(host='0.0.0.0', debug=True, port=5050) 32 | -------------------------------------------------------------------------------- /src/frontend/nginx.dev.conf: -------------------------------------------------------------------------------- 1 | events { } 2 | 3 | http { 4 | 5 | map $http_upgrade $connection_upgrade { 6 | default upgrade; 7 | '' close; 8 | } 9 | 10 | server { 11 | listen 80; 12 | server_name localhost; 13 | 14 | access_log /var/log/nginx/data-access.log combined; 15 | 16 | location / { 17 | root /usr/share/nginx/html; 18 | } 19 | 20 | location /api { 21 | proxy_pass http://backend:5000/api; 22 | proxy_set_header X-Real-IP $remote_addr; 23 | proxy_set_header X-Forwarded-For $remote_addr; 24 | proxy_set_header Host $host; 25 | proxy_set_header X-Forwarded-Proto $scheme; 26 | proxy_redirect http://backend:5000/api $scheme://$http_host/; 27 | proxy_http_version 1.1; 28 | proxy_set_header Upgrade $http_upgrade; 29 | proxy_set_header Connection $connection_upgrade; 30 | proxy_read_timeout 20d; 31 | proxy_buffering off; 32 | } 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@material-ui/core": "^4.10.0", 7 | "@material-ui/lab": "^4.0.0-alpha.54", 8 | "@testing-library/jest-dom": "^4.2.4", 9 | "@testing-library/react": "^9.3.2", 10 | "@testing-library/user-event": "^7.1.2", 11 | "axios": "^0.19.2", 12 | "react": "^16.13.1", 13 | "react-dom": "^16.13.1", 14 | "react-scripts": "3.4.1" 15 | }, 16 | "scripts": { 17 | "start": "react-scripts start", 18 | "build": "react-scripts build", 19 | "test": "react-scripts test", 20 | "eject": "react-scripts eject" 21 | }, 22 | "eslintConfig": { 23 | "extends": "react-app" 24 | }, 25 | "browserslist": { 26 | "production": [ 27 | ">0.2%", 28 | "not dead", 29 | "not op_mini all" 30 | ], 31 | "development": [ 32 | "last 1 chrome version", 33 | "last 1 firefox version", 34 | "last 1 safari version" 35 | ] 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/frontend/nginx.conf: -------------------------------------------------------------------------------- 1 | events { } 2 | 3 | http { 4 | 5 | map $http_upgrade $connection_upgrade { 6 | default upgrade; 7 | '' close; 8 | } 9 | 10 | server { 11 | server_name www.demo.ahmedbesbes.com; 12 | return 301 $scheme://demo.ahmedbesbes.com$request_uri; 13 | } 14 | 15 | server { 16 | listen 80; 17 | server_name demo.ahmedbesbes.com; 18 | return 301 https://demo.ahmedbesbes.com$request_uri; 19 | } 20 | 21 | server { 22 | listen 443 ssl; 23 | server_name demo.ahmedbesbes.com; 24 | 25 | ssl_certificate /etc/nginx/certs/fullchain.pem; 26 | ssl_certificate_key /etc/nginx/certs/privkey.pem; 27 | 28 | access_log /var/log/nginx/data-access.log combined; 29 | 30 | location / { 31 | root /usr/share/nginx/html; 32 | } 33 | 34 | location /api { 35 | proxy_pass http://backend:5000/api; 36 | proxy_set_header X-Real-IP $remote_addr; 37 | proxy_set_header X-Forwarded-For $remote_addr; 38 | proxy_set_header Host $host; 39 | proxy_set_header X-Forwarded-Proto $scheme; 40 | proxy_redirect http://backend:5000/api $scheme://$http_host/; 41 | proxy_http_version 1.1; 42 | proxy_set_header Upgrade $http_upgrade; 43 | proxy_set_header Connection $connection_upgrade; 44 | proxy_read_timeout 20d; 45 | proxy_buffering off; 46 | } 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/frontend/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `yarn start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `yarn test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `yarn build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `yarn eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | 46 | ### Code Splitting 47 | 48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 49 | 50 | ### Analyzing the Bundle Size 51 | 52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 53 | 54 | ### Making a Progressive Web App 55 | 56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 57 | 58 | ### Advanced Configuration 59 | 60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 61 | 62 | ### Deployment 63 | 64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 65 | 66 | ### `yarn build` fails to minify 67 | 68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 69 | -------------------------------------------------------------------------------- /src/frontend/src/components/BasicForm.js: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | import { makeStyles } from "@material-ui/core/styles"; 3 | import TextField from "@material-ui/core/TextField"; 4 | import Button from "@material-ui/core/Button"; 5 | import Container from "@material-ui/core/Container"; 6 | import Grid from "@material-ui/core/Grid"; 7 | import Typography from "@material-ui/core/Typography"; 8 | import Alert from "@material-ui/lab/Alert"; 9 | 10 | import axios from "axios"; 11 | 12 | const useStyles = makeStyles((theme) => ({ 13 | input: { 14 | margin: 5, 15 | }, 16 | })); 17 | 18 | export default function BasicForm() { 19 | const url = "api/submit"; 20 | const classes = useStyles(); 21 | const [identity, setIdentity] = useState({ firstName: "", lastName: "" }); 22 | const [job, setJob] = useState(""); 23 | const [success, setSuccess] = useState(undefined); 24 | 25 | function handleInputFirstName(e) { 26 | setIdentity({ ...identity, firstName: e.target.value }); 27 | } 28 | 29 | function handleInputLastName(e) { 30 | setIdentity({ ...identity, lastName: e.target.value }); 31 | } 32 | 33 | function handleInputJob(e) { 34 | setJob(e.target.value); 35 | } 36 | 37 | function handleSubmit(e) { 38 | e.preventDefault(); 39 | const data = new FormData(); 40 | data.set("firstName", identity.firstName); 41 | data.set("lastName", identity.lastName); 42 | data.set("job", job); 43 | 44 | axios({ 45 | method: "post", 46 | url: url, 47 | data: data, 48 | }) 49 | .then(function (response) { 50 | console.log(response); 51 | setSuccess(true); 52 | }) 53 | .catch(function (response) { 54 | setSuccess(false); 55 | console.log(response); 56 | }); 57 | } 58 | 59 | function Alerting() { 60 | if (success === true) { 61 | return Data sucessfully sent !; 62 | } else if (success === false) { 63 | return Oops. An error just occured!; 64 | } else { 65 | return null; 66 | } 67 | } 68 | 69 | return ( 70 | 71 |
72 | 73 | 74 | 83 | 84 | 85 | 86 | 95 | 96 | 97 | 98 | 107 | 108 | 109 | 110 | 111 | 114 |
115 | 116 |
117 |
118 |
119 |
120 |
121 |
122 | ); 123 | } 124 | -------------------------------------------------------------------------------- /src/frontend/src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' }, 105 | }) 106 | .then(response => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then(registration => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready 134 | .then(registration => { 135 | registration.unregister(); 136 | }) 137 | .catch(error => { 138 | console.error(error.message); 139 | }); 140 | } 141 | } 142 | --------------------------------------------------------------------------------