├── .gitignore ├── LICENSE ├── README.md ├── back-end ├── .gitignore ├── package-lock.json ├── package.json └── src │ ├── app.js │ ├── server.js │ ├── subscriptionHandler.js │ └── swagger.json ├── front-end-react ├── .gitignore ├── README.md ├── config │ ├── env.js │ ├── jest │ │ ├── cssTransform.js │ │ └── fileTransform.js │ ├── modules.js │ ├── paths.js │ ├── pnpTs.js │ ├── webpack.config.js │ └── webpackDevServer.config.js ├── package-lock.json ├── package.json ├── public │ ├── favicon.ico │ ├── images │ │ ├── jason-leung-HM6TMmevbZQ-unsplash.jpg │ │ └── repository-open-graph-template.png │ ├── index.html │ ├── new-product-jason-leung-HM6TMmevbZQ-unsplash.html │ ├── robots.txt │ └── sw.js ├── scripts │ ├── build.js │ ├── start.js │ └── test.js └── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── PushNotificationDemo.js │ ├── index.css │ ├── index.js │ ├── logo.svg │ ├── push-notifications.js │ ├── usePushNotifications.js │ └── utils │ └── http.js ├── front-end ├── .babelrc ├── .browserslistrc ├── .eslintrc ├── .gitignore ├── README.md ├── package.json ├── public │ ├── .gitkeep │ ├── images │ │ ├── jason-leung-HM6TMmevbZQ-unsplash.jpg │ │ └── repository-open-graph-template.png │ ├── new-product-jason-leung-HM6TMmevbZQ-unsplash.html │ └── sw.js ├── src │ ├── index.html │ ├── scripts │ │ ├── index.js │ │ ├── push-notifications.js │ │ └── utils │ │ │ └── http.js │ └── styles │ │ └── index.scss └── webpack │ ├── webpack.common.js │ ├── webpack.config.dev.js │ └── webpack.config.prod.js ├── package.json └── push-notification.jpg /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | front-end-react/yarn\.lock 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Lorenzo Spinelli 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > How to implement Web Push Notifications with live demo and instructions: https://push-notifications-demo.netlify.app/ 2 | 3 | ![A push notificatin][pushNotificaiton] 4 | 5 | [pushNotificaiton]: https://github.com/Spyna/push-notification-demo/raw/master/push-notification.jpg "Push notification" 6 | 7 | # push-notification-demo 8 | 9 | This mono-repo project is a demo for this article https://itnext.io/an-introduction-to-web-push-notifications-in-javascript-a701783917ce 10 | 11 | The project is composed by two parts: 12 | 13 | * a front end written is HTML + JavaScript 14 | 15 | * a back end written in JavaScript + NodeJS 16 | 17 | ## Run locally 18 | 19 | ### font-end 20 | 21 | ``` 22 | cd front-end 23 | npm install 24 | npm start 25 | ``` 26 | Next, open http://localhost:9000. 27 | 28 | ### back-end 29 | 30 | ``` 31 | cd back-end 32 | npm install 33 | export CORS_ORIGIN=http://localhost:9000 && node src/server.js 34 | ``` 35 | 36 | `export CORS_ORIGIN=http://localhost:9000` means: accept Cross Origin call from this host. 37 | 38 | ## deploying to your server 39 | 40 | If you want to deploy the front-end to your server remember to modify the back-end host in the webpack config file: `webpack.config.prod.js`: `'process.env.PUSH_SERVER_URL': JSON.stringify('https://push-notification-demo-server.herokuapp.com'),` 41 | 42 | [![Analytics](https://ga-beacon.appspot.com/UA-89584671-2/github/push-notification-demo)](https://github.com/igrigorik/ga-beacon) 43 | -------------------------------------------------------------------------------- /back-end/.gitignore: -------------------------------------------------------------------------------- 1 | # dependencies 2 | node_modules 3 | 4 | # production 5 | build 6 | 7 | # misc 8 | .DS_Store 9 | 10 | npm-debug.log 11 | yarn-error.log 12 | yarn.lock 13 | .yarnclean 14 | .vscode 15 | -------------------------------------------------------------------------------- /back-end/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "back-end", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "accepts": { 8 | "version": "1.3.7", 9 | "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", 10 | "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", 11 | "requires": { 12 | "mime-types": "~2.1.24", 13 | "negotiator": "0.6.2" 14 | } 15 | }, 16 | "agent-base": { 17 | "version": "4.3.0", 18 | "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-4.3.0.tgz", 19 | "integrity": "sha512-salcGninV0nPrwpGNn4VTXBb1SOuXQBiqbrNXoeizJsHrsL6ERFM2Ne3JUSBWRE6aeNJI2ROP/WEEIDUiDe3cg==", 20 | "requires": { 21 | "es6-promisify": "^5.0.0" 22 | } 23 | }, 24 | "array-flatten": { 25 | "version": "1.1.1", 26 | "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", 27 | "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" 28 | }, 29 | "asn1.js": { 30 | "version": "5.3.0", 31 | "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.3.0.tgz", 32 | "integrity": "sha512-WHnQJFcOrIWT1RLOkFFBQkFVvyt9BPOOrH+Dp152Zk4R993rSzXUGPmkybIcUFhHE2d/iHH+nCaOWVCDbO8fgA==", 33 | "requires": { 34 | "bn.js": "^4.0.0", 35 | "inherits": "^2.0.1", 36 | "minimalistic-assert": "^1.0.0", 37 | "safer-buffer": "^2.1.0" 38 | } 39 | }, 40 | "bn.js": { 41 | "version": "4.11.8", 42 | "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.8.tgz", 43 | "integrity": "sha512-ItfYfPLkWHUjckQCk8xC+LwxgK8NYcXywGigJgSwOP8Y2iyWT4f2vsZnoOXTTbo+o5yXmIUJ4gn5538SO5S3gA==" 44 | }, 45 | "body-parser": { 46 | "version": "1.19.0", 47 | "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz", 48 | "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==", 49 | "requires": { 50 | "bytes": "3.1.0", 51 | "content-type": "~1.0.4", 52 | "debug": "2.6.9", 53 | "depd": "~1.1.2", 54 | "http-errors": "1.7.2", 55 | "iconv-lite": "0.4.24", 56 | "on-finished": "~2.3.0", 57 | "qs": "6.7.0", 58 | "raw-body": "2.4.0", 59 | "type-is": "~1.6.17" 60 | } 61 | }, 62 | "buffer-equal-constant-time": { 63 | "version": "1.0.1", 64 | "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", 65 | "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" 66 | }, 67 | "bytes": { 68 | "version": "3.1.0", 69 | "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", 70 | "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==" 71 | }, 72 | "compressible": { 73 | "version": "2.0.18", 74 | "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz", 75 | "integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==", 76 | "requires": { 77 | "mime-db": ">= 1.43.0 < 2" 78 | } 79 | }, 80 | "compression": { 81 | "version": "1.7.4", 82 | "resolved": "https://registry.npmjs.org/compression/-/compression-1.7.4.tgz", 83 | "integrity": "sha512-jaSIDzP9pZVS4ZfQ+TzvtiWhdpFhE2RDHz8QJkpX9SIpLq88VueF5jJw6t+6CUQcAoA6t+x89MLrWAqpfDE8iQ==", 84 | "requires": { 85 | "accepts": "~1.3.5", 86 | "bytes": "3.0.0", 87 | "compressible": "~2.0.16", 88 | "debug": "2.6.9", 89 | "on-headers": "~1.0.2", 90 | "safe-buffer": "5.1.2", 91 | "vary": "~1.1.2" 92 | }, 93 | "dependencies": { 94 | "bytes": { 95 | "version": "3.0.0", 96 | "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", 97 | "integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=" 98 | } 99 | } 100 | }, 101 | "content-disposition": { 102 | "version": "0.5.3", 103 | "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", 104 | "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", 105 | "requires": { 106 | "safe-buffer": "5.1.2" 107 | } 108 | }, 109 | "content-type": { 110 | "version": "1.0.4", 111 | "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", 112 | "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==" 113 | }, 114 | "cookie": { 115 | "version": "0.4.0", 116 | "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", 117 | "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==" 118 | }, 119 | "cookie-signature": { 120 | "version": "1.0.6", 121 | "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", 122 | "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" 123 | }, 124 | "cors": { 125 | "version": "2.8.5", 126 | "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", 127 | "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", 128 | "requires": { 129 | "object-assign": "^4", 130 | "vary": "^1" 131 | } 132 | }, 133 | "debug": { 134 | "version": "2.6.9", 135 | "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", 136 | "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", 137 | "requires": { 138 | "ms": "2.0.0" 139 | } 140 | }, 141 | "depd": { 142 | "version": "1.1.2", 143 | "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", 144 | "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" 145 | }, 146 | "destroy": { 147 | "version": "1.0.4", 148 | "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", 149 | "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" 150 | }, 151 | "ecdsa-sig-formatter": { 152 | "version": "1.0.11", 153 | "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", 154 | "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", 155 | "requires": { 156 | "safe-buffer": "^5.0.1" 157 | } 158 | }, 159 | "ee-first": { 160 | "version": "1.1.1", 161 | "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", 162 | "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" 163 | }, 164 | "encodeurl": { 165 | "version": "1.0.2", 166 | "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", 167 | "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=" 168 | }, 169 | "es6-promise": { 170 | "version": "4.2.8", 171 | "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.8.tgz", 172 | "integrity": "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w==" 173 | }, 174 | "es6-promisify": { 175 | "version": "5.0.0", 176 | "resolved": "https://registry.npmjs.org/es6-promisify/-/es6-promisify-5.0.0.tgz", 177 | "integrity": "sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM=", 178 | "requires": { 179 | "es6-promise": "^4.0.3" 180 | } 181 | }, 182 | "escape-html": { 183 | "version": "1.0.3", 184 | "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", 185 | "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" 186 | }, 187 | "etag": { 188 | "version": "1.8.1", 189 | "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", 190 | "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=" 191 | }, 192 | "express": { 193 | "version": "4.17.1", 194 | "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz", 195 | "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==", 196 | "requires": { 197 | "accepts": "~1.3.7", 198 | "array-flatten": "1.1.1", 199 | "body-parser": "1.19.0", 200 | "content-disposition": "0.5.3", 201 | "content-type": "~1.0.4", 202 | "cookie": "0.4.0", 203 | "cookie-signature": "1.0.6", 204 | "debug": "2.6.9", 205 | "depd": "~1.1.2", 206 | "encodeurl": "~1.0.2", 207 | "escape-html": "~1.0.3", 208 | "etag": "~1.8.1", 209 | "finalhandler": "~1.1.2", 210 | "fresh": "0.5.2", 211 | "merge-descriptors": "1.0.1", 212 | "methods": "~1.1.2", 213 | "on-finished": "~2.3.0", 214 | "parseurl": "~1.3.3", 215 | "path-to-regexp": "0.1.7", 216 | "proxy-addr": "~2.0.5", 217 | "qs": "6.7.0", 218 | "range-parser": "~1.2.1", 219 | "safe-buffer": "5.1.2", 220 | "send": "0.17.1", 221 | "serve-static": "1.14.1", 222 | "setprototypeof": "1.1.1", 223 | "statuses": "~1.5.0", 224 | "type-is": "~1.6.18", 225 | "utils-merge": "1.0.1", 226 | "vary": "~1.1.2" 227 | } 228 | }, 229 | "finalhandler": { 230 | "version": "1.1.2", 231 | "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", 232 | "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", 233 | "requires": { 234 | "debug": "2.6.9", 235 | "encodeurl": "~1.0.2", 236 | "escape-html": "~1.0.3", 237 | "on-finished": "~2.3.0", 238 | "parseurl": "~1.3.3", 239 | "statuses": "~1.5.0", 240 | "unpipe": "~1.0.0" 241 | } 242 | }, 243 | "forwarded": { 244 | "version": "0.1.2", 245 | "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", 246 | "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=" 247 | }, 248 | "fresh": { 249 | "version": "0.5.2", 250 | "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", 251 | "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=" 252 | }, 253 | "http-errors": { 254 | "version": "1.7.2", 255 | "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", 256 | "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", 257 | "requires": { 258 | "depd": "~1.1.2", 259 | "inherits": "2.0.3", 260 | "setprototypeof": "1.1.1", 261 | "statuses": ">= 1.5.0 < 2", 262 | "toidentifier": "1.0.0" 263 | } 264 | }, 265 | "http_ece": { 266 | "version": "1.1.0", 267 | "resolved": "https://registry.npmjs.org/http_ece/-/http_ece-1.1.0.tgz", 268 | "integrity": "sha512-bptAfCDdPJxOs5zYSe7Y3lpr772s1G346R4Td5LgRUeCwIGpCGDUTJxRrhTNcAXbx37spge0kWEIH7QAYWNTlA==", 269 | "requires": { 270 | "urlsafe-base64": "~1.0.0" 271 | } 272 | }, 273 | "https-proxy-agent": { 274 | "version": "3.0.1", 275 | "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-3.0.1.tgz", 276 | "integrity": "sha512-+ML2Rbh6DAuee7d07tYGEKOEi2voWPUGan+ExdPbPW6Z3svq+JCqr0v8WmKPOkz1vOVykPCBSuobe7G8GJUtVg==", 277 | "requires": { 278 | "agent-base": "^4.3.0", 279 | "debug": "^3.1.0" 280 | }, 281 | "dependencies": { 282 | "debug": { 283 | "version": "3.2.6", 284 | "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", 285 | "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", 286 | "requires": { 287 | "ms": "^2.1.1" 288 | } 289 | }, 290 | "ms": { 291 | "version": "2.1.2", 292 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", 293 | "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" 294 | } 295 | } 296 | }, 297 | "iconv-lite": { 298 | "version": "0.4.24", 299 | "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", 300 | "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", 301 | "requires": { 302 | "safer-buffer": ">= 2.1.2 < 3" 303 | } 304 | }, 305 | "inherits": { 306 | "version": "2.0.3", 307 | "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", 308 | "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" 309 | }, 310 | "ipaddr.js": { 311 | "version": "1.9.1", 312 | "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", 313 | "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==" 314 | }, 315 | "jwa": { 316 | "version": "1.4.1", 317 | "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", 318 | "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", 319 | "requires": { 320 | "buffer-equal-constant-time": "1.0.1", 321 | "ecdsa-sig-formatter": "1.0.11", 322 | "safe-buffer": "^5.0.1" 323 | } 324 | }, 325 | "jws": { 326 | "version": "3.2.2", 327 | "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", 328 | "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", 329 | "requires": { 330 | "jwa": "^1.4.1", 331 | "safe-buffer": "^5.0.1" 332 | } 333 | }, 334 | "media-typer": { 335 | "version": "0.3.0", 336 | "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", 337 | "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" 338 | }, 339 | "merge-descriptors": { 340 | "version": "1.0.1", 341 | "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", 342 | "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" 343 | }, 344 | "methods": { 345 | "version": "1.1.2", 346 | "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", 347 | "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=" 348 | }, 349 | "mime": { 350 | "version": "1.6.0", 351 | "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", 352 | "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" 353 | }, 354 | "mime-db": { 355 | "version": "1.44.0", 356 | "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.44.0.tgz", 357 | "integrity": "sha512-/NOTfLrsPBVeH7YtFPgsVWveuL+4SjjYxaQ1xtM1KMFj7HdxlBlxeyNLzhyJVx7r4rZGJAZ/6lkKCitSc/Nmpg==" 358 | }, 359 | "mime-types": { 360 | "version": "2.1.27", 361 | "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.27.tgz", 362 | "integrity": "sha512-JIhqnCasI9yD+SsmkquHBxTSEuZdQX5BuQnS2Vc7puQQQ+8yiP5AY5uWhpdv4YL4VM5c6iliiYWPgJ/nJQLp7w==", 363 | "requires": { 364 | "mime-db": "1.44.0" 365 | } 366 | }, 367 | "minimalistic-assert": { 368 | "version": "1.0.1", 369 | "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", 370 | "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==" 371 | }, 372 | "minimist": { 373 | "version": "1.2.5", 374 | "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", 375 | "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" 376 | }, 377 | "ms": { 378 | "version": "2.0.0", 379 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", 380 | "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" 381 | }, 382 | "negotiator": { 383 | "version": "0.6.2", 384 | "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", 385 | "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==" 386 | }, 387 | "object-assign": { 388 | "version": "4.1.1", 389 | "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", 390 | "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=" 391 | }, 392 | "on-finished": { 393 | "version": "2.3.0", 394 | "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", 395 | "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", 396 | "requires": { 397 | "ee-first": "1.1.1" 398 | } 399 | }, 400 | "on-headers": { 401 | "version": "1.0.2", 402 | "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", 403 | "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==" 404 | }, 405 | "parseurl": { 406 | "version": "1.3.3", 407 | "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", 408 | "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==" 409 | }, 410 | "path-to-regexp": { 411 | "version": "0.1.7", 412 | "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", 413 | "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" 414 | }, 415 | "proxy-addr": { 416 | "version": "2.0.6", 417 | "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.6.tgz", 418 | "integrity": "sha512-dh/frvCBVmSsDYzw6n926jv974gddhkFPfiN8hPOi30Wax25QZyZEGveluCgliBnqmuM+UJmBErbAUFIoDbjOw==", 419 | "requires": { 420 | "forwarded": "~0.1.2", 421 | "ipaddr.js": "1.9.1" 422 | } 423 | }, 424 | "qs": { 425 | "version": "6.7.0", 426 | "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", 427 | "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==" 428 | }, 429 | "range-parser": { 430 | "version": "1.2.1", 431 | "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", 432 | "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==" 433 | }, 434 | "raw-body": { 435 | "version": "2.4.0", 436 | "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz", 437 | "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==", 438 | "requires": { 439 | "bytes": "3.1.0", 440 | "http-errors": "1.7.2", 441 | "iconv-lite": "0.4.24", 442 | "unpipe": "1.0.0" 443 | } 444 | }, 445 | "safe-buffer": { 446 | "version": "5.1.2", 447 | "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", 448 | "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" 449 | }, 450 | "safer-buffer": { 451 | "version": "2.1.2", 452 | "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", 453 | "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" 454 | }, 455 | "send": { 456 | "version": "0.17.1", 457 | "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", 458 | "integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==", 459 | "requires": { 460 | "debug": "2.6.9", 461 | "depd": "~1.1.2", 462 | "destroy": "~1.0.4", 463 | "encodeurl": "~1.0.2", 464 | "escape-html": "~1.0.3", 465 | "etag": "~1.8.1", 466 | "fresh": "0.5.2", 467 | "http-errors": "~1.7.2", 468 | "mime": "1.6.0", 469 | "ms": "2.1.1", 470 | "on-finished": "~2.3.0", 471 | "range-parser": "~1.2.1", 472 | "statuses": "~1.5.0" 473 | }, 474 | "dependencies": { 475 | "ms": { 476 | "version": "2.1.1", 477 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", 478 | "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" 479 | } 480 | } 481 | }, 482 | "serve-static": { 483 | "version": "1.14.1", 484 | "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz", 485 | "integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==", 486 | "requires": { 487 | "encodeurl": "~1.0.2", 488 | "escape-html": "~1.0.3", 489 | "parseurl": "~1.3.3", 490 | "send": "0.17.1" 491 | } 492 | }, 493 | "setprototypeof": { 494 | "version": "1.1.1", 495 | "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz", 496 | "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==" 497 | }, 498 | "statuses": { 499 | "version": "1.5.0", 500 | "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", 501 | "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=" 502 | }, 503 | "swagger-ui-dist": { 504 | "version": "3.25.1", 505 | "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-3.25.1.tgz", 506 | "integrity": "sha512-Sw/K95j1pT9TZtLKiHDEml7YqcXC9thTTQjxrvNgd9j1KzOIxpo/5lhHuUMAN/hxVAHetzmcBcQaBjywRXog8w==" 507 | }, 508 | "swagger-ui-express": { 509 | "version": "4.1.4", 510 | "resolved": "https://registry.npmjs.org/swagger-ui-express/-/swagger-ui-express-4.1.4.tgz", 511 | "integrity": "sha512-Ea96ecpC+Iq9GUqkeD/LFR32xSs8gYqmTW1gXCuKg81c26WV6ZC2FsBSPVExQP6WkyUuz5HEiR0sEv/HCC343g==", 512 | "requires": { 513 | "swagger-ui-dist": "^3.18.1" 514 | } 515 | }, 516 | "toidentifier": { 517 | "version": "1.0.0", 518 | "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", 519 | "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==" 520 | }, 521 | "type-is": { 522 | "version": "1.6.18", 523 | "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", 524 | "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", 525 | "requires": { 526 | "media-typer": "0.3.0", 527 | "mime-types": "~2.1.24" 528 | } 529 | }, 530 | "unpipe": { 531 | "version": "1.0.0", 532 | "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", 533 | "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=" 534 | }, 535 | "urlsafe-base64": { 536 | "version": "1.0.0", 537 | "resolved": "https://registry.npmjs.org/urlsafe-base64/-/urlsafe-base64-1.0.0.tgz", 538 | "integrity": "sha1-I/iQaabGL0bPOh07ABac77kL4MY=" 539 | }, 540 | "utils-merge": { 541 | "version": "1.0.1", 542 | "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", 543 | "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=" 544 | }, 545 | "vary": { 546 | "version": "1.1.2", 547 | "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", 548 | "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=" 549 | }, 550 | "web-push": { 551 | "version": "3.4.3", 552 | "resolved": "https://registry.npmjs.org/web-push/-/web-push-3.4.3.tgz", 553 | "integrity": "sha512-nt/hRSlfRDTwvem//7jle1+cy62lBoxFshad8ai2Q4SlHZS00oHnrw5Dul3jSWXR+bOcnZkwnRs3tW+daNTuyA==", 554 | "requires": { 555 | "asn1.js": "^5.0.0", 556 | "http_ece": "1.1.0", 557 | "https-proxy-agent": "^3.0.0", 558 | "jws": "^3.1.3", 559 | "minimist": "^1.2.0", 560 | "urlsafe-base64": "^1.0.0" 561 | } 562 | } 563 | } 564 | } 565 | -------------------------------------------------------------------------------- /back-end/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "back-end", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "license": "MIT", 6 | "dependencies": { 7 | "body-parser": "^1.19.0", 8 | "compression": "^1.7.4", 9 | "cors": "^2.8.5", 10 | "express": "^4.17.1", 11 | "swagger-ui-express": "^4.0.7", 12 | "web-push": "^3.3.5" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /back-end/src/app.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const compression = require("compression"); 3 | const bodyParser = require("body-parser"); 4 | const cors = require("cors"); 5 | const subscriptionHandler = require('./subscriptionHandler') 6 | 7 | const swaggerUi = require('swagger-ui-express') 8 | const swaggerDocument = require('./swagger.json'); 9 | 10 | const app = express(); 11 | 12 | app.use(cors()) 13 | app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); 14 | app.use(compression()); 15 | app.use(bodyParser.urlencoded({ extended: true })); 16 | app.use(bodyParser.json()); 17 | 18 | app.post("/subscription", subscriptionHandler.handlePushNotificationSubscription); 19 | app.get("/subscription/:id", subscriptionHandler.sendPushNotification); 20 | 21 | module.exports = app; 22 | -------------------------------------------------------------------------------- /back-end/src/server.js: -------------------------------------------------------------------------------- 1 | const app = require("./app"); 2 | 3 | const port = process.env.PORT || 8080; 4 | const host = process.env.HOSTNAME || "0.0.0.0"; 5 | 6 | // Launch Node.js server 7 | const server = app.listen(port, host, () => { 8 | console.log(`Node.js API server is listening on http://${host}:${port}/`); 9 | }); 10 | 11 | function handleExit(err) { 12 | if (err) { 13 | errors.report(err); 14 | } 15 | if (options.exit) { 16 | process.exit(); 17 | } 18 | } 19 | 20 | process.on("exit", handleExit.bind(null)); 21 | process.on("SIGINT", handleExit.bind(null)); 22 | process.on("SIGTERM", handleExit.bind(null)); 23 | process.on("uncaughtException", handleExit.bind(null)); 24 | -------------------------------------------------------------------------------- /back-end/src/subscriptionHandler.js: -------------------------------------------------------------------------------- 1 | const subscriptions = {}; 2 | var crypto = require("crypto"); 3 | const webpush = require("web-push"); 4 | 5 | const vapidKeys = { 6 | privateKey: "bdSiNzUhUP6piAxLH-tW88zfBlWWveIx0dAsDO66aVU", 7 | publicKey: "BIN2Jc5Vmkmy-S3AUrcMlpKxJpLeVRAfu9WBqUbJ70SJOCWGCGXKY-Xzyh7HDr6KbRDGYHjqZ06OcS3BjD7uAm8" 8 | }; 9 | 10 | webpush.setVapidDetails("mailto:example@yourdomain.org", vapidKeys.publicKey, vapidKeys.privateKey); 11 | 12 | function createHash(input) { 13 | const md5sum = crypto.createHash("md5"); 14 | md5sum.update(Buffer.from(input)); 15 | return md5sum.digest("hex"); 16 | } 17 | 18 | function handlePushNotificationSubscription(req, res) { 19 | const subscriptionRequest = req.body; 20 | const susbscriptionId = createHash(JSON.stringify(subscriptionRequest)); 21 | subscriptions[susbscriptionId] = subscriptionRequest; 22 | res.status(201).json({ id: susbscriptionId }); 23 | } 24 | 25 | function sendPushNotification(req, res) { 26 | const subscriptionId = req.params.id; 27 | const pushSubscription = subscriptions[subscriptionId]; 28 | webpush 29 | .sendNotification( 30 | pushSubscription, 31 | JSON.stringify({ 32 | title: "New Product Available ", 33 | text: "HEY! Take a look at this brand new t-shirt!", 34 | image: "/images/jason-leung-HM6TMmevbZQ-unsplash.jpg", 35 | tag: "new-product", 36 | url: "/new-product-jason-leung-HM6TMmevbZQ-unsplash.html" 37 | }) 38 | ) 39 | .catch(err => { 40 | console.log(err); 41 | }); 42 | 43 | res.status(202).json({}); 44 | } 45 | 46 | module.exports = { handlePushNotificationSubscription, sendPushNotification }; 47 | -------------------------------------------------------------------------------- /back-end/src/swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "swagger": "2.0", 3 | "info": { 4 | "version": "1.0.0", 5 | "title": "Push server API", 6 | "description": "Web push notification demo server", 7 | "license": { 8 | "name": "MIT", 9 | "url": "https://opensource.org/licenses/MIT" 10 | } 11 | }, 12 | "host": "push-notification-demo-server.herokuapp.com/", 13 | "basePath": "", 14 | "tags": [ 15 | { 16 | "name": "Web Push Subscription", 17 | "description": "API for Web push subscription" 18 | } 19 | ], 20 | "schemes": ["https"], 21 | "consumes": ["application/json"], 22 | "produces": ["application/json"], 23 | "paths": { 24 | "/subscription": { 25 | "post": { 26 | "tags": ["Web Push Subscription"], 27 | "description": "Recevies a push subscription and save it in memory", 28 | "parameters": [ 29 | { 30 | "name": "pushSubscription", 31 | "in": "body", 32 | "description": "the subscription to be saved", 33 | "schema": { 34 | "$ref": "#/definitions/pushSubscription" 35 | } 36 | } 37 | ], 38 | "produces": ["application/json"], 39 | "responses": { 40 | "201": { 41 | "description": "everything ok", 42 | "schema": { 43 | "$ref": "#/definitions/pushSubscriptionResponse" 44 | } 45 | } 46 | } 47 | } 48 | }, 49 | "/subscription/{id}": { 50 | "parameters": [ 51 | { 52 | "name": "id", 53 | "in": "path", 54 | "required": true, 55 | "description": "ID of the subscription that we want to find", 56 | "type": "string" 57 | } 58 | ], 59 | "get": { 60 | "tags": ["Web Push Subscription"], 61 | "summary": "Sends a push message to the existing push subscription", 62 | "responses": { 63 | "202": { 64 | "description": "Message sent" 65 | } 66 | } 67 | } 68 | } 69 | }, 70 | "definitions": { 71 | "pushSubscription": { 72 | "required": ["endpoint"], 73 | "properties": { 74 | "endpoint": { 75 | "type": "string", 76 | "uniqueItems": true 77 | }, 78 | "expirationTime": { 79 | "type": "string", 80 | "uniqueItems": true 81 | }, 82 | "keys": { 83 | "$ref": "#/definitions/Keys" 84 | } 85 | } 86 | }, 87 | "Keys": { 88 | "properties": { 89 | "p256dh": { 90 | "type": "string", 91 | "uniqueItems": true 92 | }, 93 | "auth": { 94 | "type": "string", 95 | "uniqueItems": true 96 | } 97 | } 98 | }, 99 | "pushSubscriptionResponse": { 100 | "required": ["id"], 101 | "properties": { 102 | "id": { 103 | "type": "string", 104 | "uniqueItems": true 105 | } 106 | } 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /front-end-react/.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 | -------------------------------------------------------------------------------- /front-end-react/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 | ### `npm 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 | ### `npm 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 | ### `npm run 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 | ### `npm run 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 | ### `npm run 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 | -------------------------------------------------------------------------------- /front-end-react/config/env.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const paths = require('./paths'); 6 | 7 | // Make sure that including paths.js after env.js will read .env variables. 8 | delete require.cache[require.resolve('./paths')]; 9 | 10 | const NODE_ENV = process.env.NODE_ENV; 11 | if (!NODE_ENV) { 12 | throw new Error( 13 | 'The NODE_ENV environment variable is required but was not specified.' 14 | ); 15 | } 16 | 17 | // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use 18 | var dotenvFiles = [ 19 | `${paths.dotenv}.${NODE_ENV}.local`, 20 | `${paths.dotenv}.${NODE_ENV}`, 21 | // Don't include `.env.local` for `test` environment 22 | // since normally you expect tests to produce the same 23 | // results for everyone 24 | NODE_ENV !== 'test' && `${paths.dotenv}.local`, 25 | paths.dotenv, 26 | ].filter(Boolean); 27 | 28 | // Load environment variables from .env* files. Suppress warnings using silent 29 | // if this file is missing. dotenv will never modify any environment variables 30 | // that have already been set. Variable expansion is supported in .env files. 31 | // https://github.com/motdotla/dotenv 32 | // https://github.com/motdotla/dotenv-expand 33 | dotenvFiles.forEach(dotenvFile => { 34 | if (fs.existsSync(dotenvFile)) { 35 | require('dotenv-expand')( 36 | require('dotenv').config({ 37 | path: dotenvFile, 38 | }) 39 | ); 40 | } 41 | }); 42 | 43 | // We support resolving modules according to `NODE_PATH`. 44 | // This lets you use absolute paths in imports inside large monorepos: 45 | // https://github.com/facebook/create-react-app/issues/253. 46 | // It works similar to `NODE_PATH` in Node itself: 47 | // https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders 48 | // Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. 49 | // Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims. 50 | // https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421 51 | // We also resolve them to make sure all tools using them work consistently. 52 | const appDirectory = fs.realpathSync(process.cwd()); 53 | process.env.NODE_PATH = (process.env.NODE_PATH || '') 54 | .split(path.delimiter) 55 | .filter(folder => folder && !path.isAbsolute(folder)) 56 | .map(folder => path.resolve(appDirectory, folder)) 57 | .join(path.delimiter); 58 | 59 | // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be 60 | // injected into the application via DefinePlugin in Webpack configuration. 61 | const REACT_APP = /^REACT_APP_/i; 62 | 63 | function getClientEnvironment(publicUrl) { 64 | const raw = Object.keys(process.env) 65 | .filter(key => REACT_APP.test(key)) 66 | .reduce( 67 | (env, key) => { 68 | env[key] = process.env[key]; 69 | return env; 70 | }, 71 | { 72 | // Useful for determining whether we’re running in production mode. 73 | // Most importantly, it switches React into the correct mode. 74 | NODE_ENV: process.env.NODE_ENV || 'development', 75 | // Useful for resolving the correct path to static assets in `public`. 76 | // For example, . 77 | // This should only be used as an escape hatch. Normally you would put 78 | // images into the `src` and `import` them in code to get their paths. 79 | PUBLIC_URL: publicUrl, 80 | } 81 | ); 82 | // Stringify all values so we can feed into Webpack DefinePlugin 83 | const stringified = { 84 | 'process.env': Object.keys(raw).reduce((env, key) => { 85 | env[key] = JSON.stringify(raw[key]); 86 | return env; 87 | }, {}), 88 | }; 89 | 90 | return { raw, stringified }; 91 | } 92 | 93 | module.exports = getClientEnvironment; 94 | -------------------------------------------------------------------------------- /front-end-react/config/jest/cssTransform.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // This is a custom Jest transformer turning style imports into empty objects. 4 | // http://facebook.github.io/jest/docs/en/webpack.html 5 | 6 | module.exports = { 7 | process() { 8 | return 'module.exports = {};'; 9 | }, 10 | getCacheKey() { 11 | // The output is always the same. 12 | return 'cssTransform'; 13 | }, 14 | }; 15 | -------------------------------------------------------------------------------- /front-end-react/config/jest/fileTransform.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const camelcase = require('camelcase'); 5 | 6 | // This is a custom Jest transformer turning file imports into filenames. 7 | // http://facebook.github.io/jest/docs/en/webpack.html 8 | 9 | module.exports = { 10 | process(src, filename) { 11 | const assetFilename = JSON.stringify(path.basename(filename)); 12 | 13 | if (filename.match(/\.svg$/)) { 14 | // Based on how SVGR generates a component name: 15 | // https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6 16 | const pascalCaseFileName = camelcase(path.parse(filename).name, { 17 | pascalCase: true, 18 | }); 19 | const componentName = `Svg${pascalCaseFileName}`; 20 | return `const React = require('react'); 21 | module.exports = { 22 | __esModule: true, 23 | default: ${assetFilename}, 24 | ReactComponent: React.forwardRef(function ${componentName}(props, ref) { 25 | return { 26 | $$typeof: Symbol.for('react.element'), 27 | type: 'svg', 28 | ref: ref, 29 | key: null, 30 | props: Object.assign({}, props, { 31 | children: ${assetFilename} 32 | }) 33 | }; 34 | }), 35 | };`; 36 | } 37 | 38 | return `module.exports = ${assetFilename};`; 39 | }, 40 | }; 41 | -------------------------------------------------------------------------------- /front-end-react/config/modules.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const paths = require('./paths'); 6 | const chalk = require('react-dev-utils/chalk'); 7 | const resolve = require('resolve'); 8 | 9 | /** 10 | * Get the baseUrl of a compilerOptions object. 11 | * 12 | * @param {Object} options 13 | */ 14 | function getAdditionalModulePaths(options = {}) { 15 | const baseUrl = options.baseUrl; 16 | 17 | // We need to explicitly check for null and undefined (and not a falsy value) because 18 | // TypeScript treats an empty string as `.`. 19 | if (baseUrl == null) { 20 | // If there's no baseUrl set we respect NODE_PATH 21 | // Note that NODE_PATH is deprecated and will be removed 22 | // in the next major release of create-react-app. 23 | 24 | const nodePath = process.env.NODE_PATH || ''; 25 | return nodePath.split(path.delimiter).filter(Boolean); 26 | } 27 | 28 | const baseUrlResolved = path.resolve(paths.appPath, baseUrl); 29 | 30 | // We don't need to do anything if `baseUrl` is set to `node_modules`. This is 31 | // the default behavior. 32 | if (path.relative(paths.appNodeModules, baseUrlResolved) === '') { 33 | return null; 34 | } 35 | 36 | // Allow the user set the `baseUrl` to `appSrc`. 37 | if (path.relative(paths.appSrc, baseUrlResolved) === '') { 38 | return [paths.appSrc]; 39 | } 40 | 41 | // Otherwise, throw an error. 42 | throw new Error( 43 | chalk.red.bold( 44 | "Your project's `baseUrl` can only be set to `src` or `node_modules`." + 45 | ' Create React App does not support other values at this time.' 46 | ) 47 | ); 48 | } 49 | 50 | function getModules() { 51 | // Check if TypeScript is setup 52 | const hasTsConfig = fs.existsSync(paths.appTsConfig); 53 | const hasJsConfig = fs.existsSync(paths.appJsConfig); 54 | 55 | if (hasTsConfig && hasJsConfig) { 56 | throw new Error( 57 | 'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.' 58 | ); 59 | } 60 | 61 | let config; 62 | 63 | // If there's a tsconfig.json we assume it's a 64 | // TypeScript project and set up the config 65 | // based on tsconfig.json 66 | if (hasTsConfig) { 67 | const ts = require(resolve.sync('typescript', { 68 | basedir: paths.appNodeModules, 69 | })); 70 | config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config; 71 | // Otherwise we'll check if there is jsconfig.json 72 | // for non TS projects. 73 | } else if (hasJsConfig) { 74 | config = require(paths.appJsConfig); 75 | } 76 | 77 | config = config || {}; 78 | const options = config.compilerOptions || {}; 79 | 80 | const additionalModulePaths = getAdditionalModulePaths(options); 81 | 82 | return { 83 | additionalModulePaths: additionalModulePaths, 84 | hasTsConfig, 85 | }; 86 | } 87 | 88 | module.exports = getModules(); 89 | -------------------------------------------------------------------------------- /front-end-react/config/paths.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const fs = require('fs'); 5 | const url = require('url'); 6 | 7 | // Make sure any symlinks in the project folder are resolved: 8 | // https://github.com/facebook/create-react-app/issues/637 9 | const appDirectory = fs.realpathSync(process.cwd()); 10 | const resolveApp = relativePath => path.resolve(appDirectory, relativePath); 11 | 12 | const envPublicUrl = process.env.PUBLIC_URL; 13 | 14 | function ensureSlash(inputPath, needsSlash) { 15 | const hasSlash = inputPath.endsWith('/'); 16 | if (hasSlash && !needsSlash) { 17 | return inputPath.substr(0, inputPath.length - 1); 18 | } else if (!hasSlash && needsSlash) { 19 | return `${inputPath}/`; 20 | } else { 21 | return inputPath; 22 | } 23 | } 24 | 25 | const getPublicUrl = appPackageJson => 26 | envPublicUrl || require(appPackageJson).homepage; 27 | 28 | // We use `PUBLIC_URL` environment variable or "homepage" field to infer 29 | // "public path" at which the app is served. 30 | // Webpack needs to know it to put the right 6 | 13 | 14 | 15 | 16 | Web Push notifications with React hooks demo 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 |
36 | 37 | 38 | -------------------------------------------------------------------------------- /front-end-react/public/new-product-jason-leung-HM6TMmevbZQ-unsplash.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Jason leung t-shirt 5 | 6 | 20 | 21 | 22 |

Congratulation! You clicked the notification.

23 | some t-shirts 24 |

This is the amazing t-shirt

25 | 26 | 27 | -------------------------------------------------------------------------------- /front-end-react/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /front-end-react/public/sw.js: -------------------------------------------------------------------------------- 1 | function receivePushNotification(event) { 2 | console.log("[Service Worker] Push Received."); 3 | 4 | const { image, tag, url, title, text } = event.data.json(); 5 | 6 | const options = { 7 | data: url, 8 | body: text, 9 | icon: image, 10 | vibrate: [200, 100, 200], 11 | tag: tag, 12 | image: image, 13 | badge: "https://spyna.it/icons/favicon.ico", 14 | actions: [{ action: "Detail", title: "View", icon: "https://via.placeholder.com/128/ff0000" }] 15 | }; 16 | event.waitUntil(self.registration.showNotification(title, options)); 17 | } 18 | 19 | function openPushNotification(event) { 20 | console.log("[Service Worker] Notification click Received.", event.notification.data); 21 | 22 | event.notification.close(); 23 | event.waitUntil(clients.openWindow(event.notification.data)); 24 | } 25 | 26 | self.addEventListener("push", receivePushNotification); 27 | self.addEventListener("notificationclick", openPushNotification); 28 | -------------------------------------------------------------------------------- /front-end-react/scripts/build.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Do this as the first thing so that any code reading it knows the right env. 4 | process.env.BABEL_ENV = 'production'; 5 | process.env.NODE_ENV = 'production'; 6 | 7 | // Makes the script crash on unhandled rejections instead of silently 8 | // ignoring them. In the future, promise rejections that are not handled will 9 | // terminate the Node.js process with a non-zero exit code. 10 | process.on('unhandledRejection', err => { 11 | throw err; 12 | }); 13 | 14 | // Ensure environment variables are read. 15 | require('../config/env'); 16 | 17 | 18 | const path = require('path'); 19 | const chalk = require('react-dev-utils/chalk'); 20 | const fs = require('fs-extra'); 21 | const webpack = require('webpack'); 22 | const configFactory = require('../config/webpack.config'); 23 | const paths = require('../config/paths'); 24 | const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); 25 | const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); 26 | const printHostingInstructions = require('react-dev-utils/printHostingInstructions'); 27 | const FileSizeReporter = require('react-dev-utils/FileSizeReporter'); 28 | const printBuildError = require('react-dev-utils/printBuildError'); 29 | 30 | const measureFileSizesBeforeBuild = 31 | FileSizeReporter.measureFileSizesBeforeBuild; 32 | const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild; 33 | const useYarn = fs.existsSync(paths.yarnLockFile); 34 | 35 | // These sizes are pretty large. We'll warn for bundles exceeding them. 36 | const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024; 37 | const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024; 38 | 39 | const isInteractive = process.stdout.isTTY; 40 | 41 | // Warn and crash if required files are missing 42 | if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { 43 | process.exit(1); 44 | } 45 | 46 | // Generate configuration 47 | const config = configFactory('production'); 48 | 49 | // We require that you explicitly set browsers and do not fall back to 50 | // browserslist defaults. 51 | const { checkBrowsers } = require('react-dev-utils/browsersHelper'); 52 | checkBrowsers(paths.appPath, isInteractive) 53 | .then(() => { 54 | // First, read the current file sizes in build directory. 55 | // This lets us display how much they changed later. 56 | return measureFileSizesBeforeBuild(paths.appBuild); 57 | }) 58 | .then(previousFileSizes => { 59 | // Remove all content but keep the directory so that 60 | // if you're in it, you don't end up in Trash 61 | fs.emptyDirSync(paths.appBuild); 62 | // Merge with the public folder 63 | copyPublicFolder(); 64 | // Start the webpack build 65 | return build(previousFileSizes); 66 | }) 67 | .then( 68 | ({ stats, previousFileSizes, warnings }) => { 69 | if (warnings.length) { 70 | console.log(chalk.yellow('Compiled with warnings.\n')); 71 | console.log(warnings.join('\n\n')); 72 | console.log( 73 | '\nSearch for the ' + 74 | chalk.underline(chalk.yellow('keywords')) + 75 | ' to learn more about each warning.' 76 | ); 77 | console.log( 78 | 'To ignore, add ' + 79 | chalk.cyan('// eslint-disable-next-line') + 80 | ' to the line before.\n' 81 | ); 82 | } else { 83 | console.log(chalk.green('Compiled successfully.\n')); 84 | } 85 | 86 | console.log('File sizes after gzip:\n'); 87 | printFileSizesAfterBuild( 88 | stats, 89 | previousFileSizes, 90 | paths.appBuild, 91 | WARN_AFTER_BUNDLE_GZIP_SIZE, 92 | WARN_AFTER_CHUNK_GZIP_SIZE 93 | ); 94 | console.log(); 95 | 96 | const appPackage = require(paths.appPackageJson); 97 | const publicUrl = paths.publicUrl; 98 | const publicPath = config.output.publicPath; 99 | const buildFolder = path.relative(process.cwd(), paths.appBuild); 100 | printHostingInstructions( 101 | appPackage, 102 | publicUrl, 103 | publicPath, 104 | buildFolder, 105 | useYarn 106 | ); 107 | }, 108 | err => { 109 | console.log(chalk.red('Failed to compile.\n')); 110 | printBuildError(err); 111 | process.exit(1); 112 | } 113 | ) 114 | .catch(err => { 115 | if (err && err.message) { 116 | console.log(err.message); 117 | } 118 | process.exit(1); 119 | }); 120 | 121 | // Create the production build and print the deployment instructions. 122 | function build(previousFileSizes) { 123 | // We used to support resolving modules according to `NODE_PATH`. 124 | // This now has been deprecated in favor of jsconfig/tsconfig.json 125 | // This lets you use absolute paths in imports inside large monorepos: 126 | if (process.env.NODE_PATH) { 127 | console.log( 128 | chalk.yellow( 129 | 'Setting NODE_PATH to resolve modules absolutely has been deprecated in favor of setting baseUrl in jsconfig.json (or tsconfig.json if you are using TypeScript) and will be removed in a future major release of create-react-app.' 130 | ) 131 | ); 132 | console.log(); 133 | } 134 | 135 | console.log('Creating an optimized production build...'); 136 | 137 | const compiler = webpack(config); 138 | return new Promise((resolve, reject) => { 139 | compiler.run((err, stats) => { 140 | let messages; 141 | if (err) { 142 | if (!err.message) { 143 | return reject(err); 144 | } 145 | messages = formatWebpackMessages({ 146 | errors: [err.message], 147 | warnings: [], 148 | }); 149 | } else { 150 | messages = formatWebpackMessages( 151 | stats.toJson({ all: false, warnings: true, errors: true }) 152 | ); 153 | } 154 | if (messages.errors.length) { 155 | // Only keep the first error. Others are often indicative 156 | // of the same problem, but confuse the reader with noise. 157 | if (messages.errors.length > 1) { 158 | messages.errors.length = 1; 159 | } 160 | return reject(new Error(messages.errors.join('\n\n'))); 161 | } 162 | if ( 163 | process.env.CI && 164 | (typeof process.env.CI !== 'string' || 165 | process.env.CI.toLowerCase() !== 'false') && 166 | messages.warnings.length 167 | ) { 168 | console.log( 169 | chalk.yellow( 170 | '\nTreating warnings as errors because process.env.CI = true.\n' + 171 | 'Most CI servers set it automatically.\n' 172 | ) 173 | ); 174 | return reject(new Error(messages.warnings.join('\n\n'))); 175 | } 176 | 177 | return resolve({ 178 | stats, 179 | previousFileSizes, 180 | warnings: messages.warnings, 181 | }); 182 | }); 183 | }); 184 | } 185 | 186 | function copyPublicFolder() { 187 | fs.copySync(paths.appPublic, paths.appBuild, { 188 | dereference: true, 189 | filter: file => file !== paths.appHtml, 190 | }); 191 | } 192 | -------------------------------------------------------------------------------- /front-end-react/scripts/start.js: -------------------------------------------------------------------------------- 1 | // Do this as the first thing so that any code reading it knows the right env. 2 | process.env.BABEL_ENV = "development"; 3 | process.env.NODE_ENV = "development"; 4 | 5 | // Makes the script crash on unhandled rejections instead of silently 6 | // ignoring them. In the future, promise rejections that are not handled will 7 | // terminate the Node.js process with a non-zero exit code. 8 | process.on("unhandledRejection", err => { 9 | throw err; 10 | }); 11 | 12 | // Ensure environment variables are read. 13 | require("../config/env"); 14 | 15 | const fs = require("fs"); 16 | const chalk = require("react-dev-utils/chalk"); 17 | const webpack = require("webpack"); 18 | const WebpackDevServer = require("webpack-dev-server"); 19 | const clearConsole = require("react-dev-utils/clearConsole"); 20 | const checkRequiredFiles = require("react-dev-utils/checkRequiredFiles"); 21 | const { choosePort, createCompiler, prepareProxy, prepareUrls } = require("react-dev-utils/WebpackDevServerUtils"); 22 | const openBrowser = require("react-dev-utils/openBrowser"); 23 | const paths = require("../config/paths"); 24 | const configFactory = require("../config/webpack.config"); 25 | const createDevServerConfig = require("../config/webpackDevServer.config"); 26 | 27 | const useYarn = fs.existsSync(paths.yarnLockFile); 28 | const isInteractive = process.stdout.isTTY; 29 | 30 | // Warn and crash if required files are missing 31 | if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { 32 | process.exit(1); 33 | } 34 | 35 | // Tools like Cloud9 rely on this. 36 | const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; 37 | const HOST = process.env.HOST || "0.0.0.0"; 38 | 39 | if (process.env.HOST) { 40 | console.log(chalk.cyan(`Attempting to bind to HOST environment variable: ${chalk.yellow(chalk.bold(process.env.HOST))}`)); 41 | console.log(`If this was unintentional, check that you haven't mistakenly set it in your shell.`); 42 | console.log(`Learn more here: ${chalk.yellow("https://bit.ly/CRA-advanced-config")}`); 43 | console.log(); 44 | } 45 | 46 | // We require that you explicitly set browsers and do not fall back to 47 | // browserslist defaults. 48 | const { checkBrowsers } = require("react-dev-utils/browsersHelper"); 49 | checkBrowsers(paths.appPath, isInteractive) 50 | .then(() => { 51 | // We attempt to use the default port but if it is busy, we offer the user to 52 | // run on a different port. `choosePort()` Promise resolves to the next free port. 53 | return choosePort(HOST, DEFAULT_PORT); 54 | }) 55 | .then(port => { 56 | if (port == null) { 57 | // We have not found a port. 58 | return; 59 | } 60 | const config = configFactory("development"); 61 | const protocol = process.env.HTTPS === "true" ? "https" : "http"; 62 | const appName = require(paths.appPackageJson).name; 63 | const useTypeScript = fs.existsSync(paths.appTsConfig); 64 | const urls = prepareUrls(protocol, HOST, port); 65 | const devSocket = { 66 | warnings: warnings => devServer.sockWrite(devServer.sockets, "warnings", warnings), 67 | errors: errors => devServer.sockWrite(devServer.sockets, "errors", errors) 68 | }; 69 | // Create a webpack compiler that is configured with custom messages. 70 | const compiler = createCompiler({ 71 | appName, 72 | config, 73 | devSocket, 74 | urls, 75 | useYarn, 76 | useTypeScript, 77 | webpack 78 | }); 79 | // Load proxy config 80 | const proxySetting = require(paths.appPackageJson).proxy; 81 | const proxyConfig = prepareProxy(proxySetting, paths.appPublic); 82 | // Serve webpack assets generated by the compiler over a web server. 83 | const serverConfig = createDevServerConfig(proxyConfig, urls.lanUrlForConfig); 84 | const devServer = new WebpackDevServer(compiler, serverConfig); 85 | // Launch WebpackDevServer. 86 | devServer.listen(port, HOST, err => { 87 | if (err) { 88 | return console.log(err); 89 | } 90 | if (isInteractive) { 91 | clearConsole(); 92 | } 93 | 94 | // We used to support resolving modules according to `NODE_PATH`. 95 | // This now has been deprecated in favor of jsconfig/tsconfig.json 96 | // This lets you use absolute paths in imports inside large monorepos: 97 | if (process.env.NODE_PATH) { 98 | console.log( 99 | chalk.yellow( 100 | "Setting NODE_PATH to resolve modules absolutely has been deprecated in favor of setting baseUrl in jsconfig.json (or tsconfig.json if you are using TypeScript) and will be removed in a future major release of create-react-app." 101 | ) 102 | ); 103 | console.log(); 104 | } 105 | 106 | console.log(chalk.cyan("Starting the development server...\n")); 107 | openBrowser(urls.localUrlForBrowser); 108 | }); 109 | 110 | ["SIGINT", "SIGTERM"].forEach(function(sig) { 111 | process.on(sig, function() { 112 | devServer.close(); 113 | process.exit(); 114 | }); 115 | }); 116 | }) 117 | .catch(err => { 118 | if (err && err.message) { 119 | console.log(err.message); 120 | } 121 | process.exit(1); 122 | }); 123 | -------------------------------------------------------------------------------- /front-end-react/scripts/test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Do this as the first thing so that any code reading it knows the right env. 4 | process.env.BABEL_ENV = 'test'; 5 | process.env.NODE_ENV = 'test'; 6 | process.env.PUBLIC_URL = ''; 7 | 8 | // Makes the script crash on unhandled rejections instead of silently 9 | // ignoring them. In the future, promise rejections that are not handled will 10 | // terminate the Node.js process with a non-zero exit code. 11 | process.on('unhandledRejection', err => { 12 | throw err; 13 | }); 14 | 15 | // Ensure environment variables are read. 16 | require('../config/env'); 17 | 18 | 19 | const jest = require('jest'); 20 | const execSync = require('child_process').execSync; 21 | let argv = process.argv.slice(2); 22 | 23 | function isInGitRepository() { 24 | try { 25 | execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' }); 26 | return true; 27 | } catch (e) { 28 | return false; 29 | } 30 | } 31 | 32 | function isInMercurialRepository() { 33 | try { 34 | execSync('hg --cwd . root', { stdio: 'ignore' }); 35 | return true; 36 | } catch (e) { 37 | return false; 38 | } 39 | } 40 | 41 | // Watch unless on CI or explicitly running all tests 42 | if ( 43 | !process.env.CI && 44 | argv.indexOf('--watchAll') === -1 && 45 | argv.indexOf('--watchAll=false') === -1 46 | ) { 47 | // https://github.com/facebook/create-react-app/issues/5210 48 | const hasSourceControl = isInGitRepository() || isInMercurialRepository(); 49 | argv.push(hasSourceControl ? '--watch' : '--watchAll'); 50 | } 51 | 52 | 53 | jest.run(argv); 54 | -------------------------------------------------------------------------------- /front-end-react/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | background-color: #282c34; 4 | min-height: 100vh; 5 | color: white; 6 | padding: 10px; 7 | } 8 | 9 | a, 10 | a:visited { 11 | color: white; 12 | line-height: 1.2rem; 13 | font-size: 1.2rem; 14 | } 15 | 16 | a:hover { 17 | border-bottom: 1px solid #ccc; 18 | } 19 | 20 | button { 21 | padding: 10px 20px; 22 | background-color: rgba(0, 0, 0, 0.4); 23 | border: 2px solid white; 24 | border-radius: 30px; 25 | font-size: 1.3rem; 26 | color: white; 27 | margin: 5px; 28 | cursor: pointer; 29 | } 30 | 31 | button:disabled { 32 | /* background-color: #aaa; */ 33 | background-color: rgba(0, 0, 0, 0.2); 34 | color: #999; 35 | border: 2px solid #777; 36 | cursor: not-allowed; 37 | } 38 | 39 | pre, 40 | code { 41 | text-align: left; 42 | display: block; 43 | border: 1px solid #ccc; 44 | padding: 5px; 45 | overflow-x: auto; 46 | white-space: pre-wrap; 47 | white-space: -moz-pre-wrap; 48 | white-space: -pre-wrap; 49 | white-space: -o-pre-wrap; 50 | word-wrap: break-word; 51 | max-width: 100%; 52 | word-wrap: break-word; 53 | } 54 | 55 | .app-error { 56 | margin: 20px auto; 57 | border: 2px solid yellow; 58 | background-color: orange; 59 | border-radius: 10px; 60 | font-size: 1.2rem; 61 | text-align: left; 62 | padding: 20px; 63 | width: 300px; 64 | max-width: 95vw; 65 | } 66 | 67 | .app-loader { 68 | position: fixed; 69 | top: 0; 70 | left: 0; 71 | width: 100vw; 72 | height: 100vh; 73 | display: flex; 74 | justify-content: center; 75 | align-items: center; 76 | align-content: center; 77 | z-index: 10; 78 | background-color: #282c34; 79 | opacity: 0.9; 80 | font-size: 3rem; 81 | } 82 | -------------------------------------------------------------------------------- /front-end-react/src/App.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./App.css"; 3 | import PushNotificationDemo from "./PushNotificationDemo"; 4 | 5 | function App() { 6 | return ( 7 |
8 |

React Web Push notification demo

9 |

10 | Read the docs -{` `} 11 | View the source code 12 |

13 | 14 |
15 | ); 16 | } 17 | 18 | export default App; 19 | -------------------------------------------------------------------------------- /front-end-react/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /front-end-react/src/PushNotificationDemo.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import usePushNotifications from "./usePushNotifications"; 3 | 4 | const Loading = ({ loading }) => (loading ?
Please wait, we are loading something...
: null); 5 | const Error = ({ error }) => 6 | error ? ( 7 |
8 |

{error.name}

9 |

Error message : {error.message}

10 |

Error code : {error.code}

11 |
12 | ) : null; 13 | 14 | export default function PushNotificationDemo() { 15 | const { 16 | userConsent, 17 | pushNotificationSupported, 18 | userSubscription, 19 | onClickAskUserPermission, 20 | onClickSusbribeToPushNotification, 21 | onClickSendSubscriptionToPushServer, 22 | pushServerSubscriptionId, 23 | onClickSendNotification, 24 | error, 25 | loading 26 | } = usePushNotifications(); 27 | 28 | const isConsentGranted = userConsent === "granted"; 29 | 30 | return ( 31 |
32 | 33 | 34 |

Push notification are {!pushNotificationSupported && "NOT"} supported by your device.

35 | 36 |

37 | User consent to recevie push notificaitons is {userConsent}. 38 |

39 | 40 | 41 | 42 | 45 | 46 | 49 | 50 | 53 | 54 | {pushServerSubscriptionId && ( 55 |
56 |

The server accepted the push subscrption!

57 | 58 |
59 | )} 60 | 61 |
62 |

Your notification subscription details

63 |
64 |           {JSON.stringify(userSubscription, null, " ")}
65 |         
66 |
67 |
68 | ); 69 | } 70 | -------------------------------------------------------------------------------- /front-end-react/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 4 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /front-end-react/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | 6 | ReactDOM.render(, document.getElementById('root')); 7 | -------------------------------------------------------------------------------- /front-end-react/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /front-end-react/src/push-notifications.js: -------------------------------------------------------------------------------- 1 | const pushServerPublicKey = "BIN2Jc5Vmkmy-S3AUrcMlpKxJpLeVRAfu9WBqUbJ70SJOCWGCGXKY-Xzyh7HDr6KbRDGYHjqZ06OcS3BjD7uAm8"; 2 | 3 | /** 4 | * checks if Push notification and service workers are supported by your browser 5 | */ 6 | function isPushNotificationSupported() { 7 | return "serviceWorker" in navigator && "PushManager" in window; 8 | } 9 | 10 | /** 11 | * asks user consent to receive push notifications and returns the response of the user, one of granted, default, denied 12 | */ 13 | async function askUserPermission() { 14 | return await Notification.requestPermission(); 15 | } 16 | /** 17 | * shows a notification 18 | */ 19 | function sendNotification() { 20 | const img = "/images/jason-leung-HM6TMmevbZQ-unsplash.jpg"; 21 | const text = "Take a look at this brand new t-shirt!"; 22 | const title = "New Product Available"; 23 | const options = { 24 | body: text, 25 | icon: "/images/jason-leung-HM6TMmevbZQ-unsplash.jpg", 26 | vibrate: [200, 100, 200], 27 | tag: "new-product", 28 | image: img, 29 | badge: "https://spyna.it/icons/android-icon-192x192.png", 30 | actions: [{ action: "Detail", title: "View", icon: "https://via.placeholder.com/128/ff0000" }] 31 | }; 32 | navigator.serviceWorker.ready.then(function(serviceWorker) { 33 | serviceWorker.showNotification(title, options); 34 | }); 35 | } 36 | 37 | /** 38 | * 39 | */ 40 | function registerServiceWorker() { 41 | return navigator.serviceWorker.register("/sw.js"); 42 | } 43 | 44 | /** 45 | * 46 | * using the registered service worker creates a push notification subscription and returns it 47 | * 48 | */ 49 | async function createNotificationSubscription() { 50 | //wait for service worker installation to be ready 51 | const serviceWorker = await navigator.serviceWorker.ready; 52 | // subscribe and return the subscription 53 | return await serviceWorker.pushManager.subscribe({ 54 | userVisibleOnly: true, 55 | applicationServerKey: pushServerPublicKey 56 | }); 57 | } 58 | 59 | /** 60 | * returns the subscription if present or nothing 61 | */ 62 | function getUserSubscription() { 63 | //wait for service worker installation to be ready, and then 64 | return navigator.serviceWorker.ready 65 | .then(function(serviceWorker) { 66 | return serviceWorker.pushManager.getSubscription(); 67 | }) 68 | .then(function(pushSubscription) { 69 | return pushSubscription; 70 | }); 71 | } 72 | 73 | export { 74 | isPushNotificationSupported, 75 | askUserPermission, 76 | registerServiceWorker, 77 | sendNotification, 78 | createNotificationSubscription, 79 | getUserSubscription 80 | }; 81 | -------------------------------------------------------------------------------- /front-end-react/src/usePushNotifications.js: -------------------------------------------------------------------------------- 1 | import { useState, useEffect } from "react"; 2 | import http from "./utils/http"; 3 | //the function to call the push server: https://github.com/Spyna/push-notification-demo/blob/master/front-end-react/src/utils/http.js 4 | 5 | import { 6 | isPushNotificationSupported, 7 | askUserPermission, 8 | registerServiceWorker, 9 | createNotificationSubscription, 10 | getUserSubscription 11 | } from "./push-notifications"; 12 | //import all the function created to manage the push notifications 13 | 14 | const pushNotificationSupported = isPushNotificationSupported(); 15 | //first thing to do: check if the push notifications are supported by the browser 16 | 17 | export default function usePushNotifications() { 18 | const [userConsent, setSuserConsent] = useState(Notification.permission); 19 | //to manage the user consent: Notification.permission is a JavaScript native function that return the current state of the permission 20 | //We initialize the userConsent with that value 21 | const [userSubscription, setUserSubscription] = useState(null); 22 | //to manage the use push notification subscription 23 | const [pushServerSubscriptionId, setPushServerSubscriptionId] = useState(); 24 | //to manage the push server subscription 25 | const [error, setError] = useState(null); 26 | //to manage errors 27 | const [loading, setLoading] = useState(true); 28 | //to manage async actions 29 | 30 | useEffect(() => { 31 | if (pushNotificationSupported) { 32 | setLoading(true); 33 | setError(false); 34 | registerServiceWorker().then(() => { 35 | setLoading(false); 36 | }); 37 | } 38 | }, []); 39 | //if the push notifications are supported, registers the service worker 40 | //this effect runs only the first render 41 | 42 | useEffect(() => { 43 | setLoading(true); 44 | setError(false); 45 | const getExixtingSubscription = async () => { 46 | const existingSubscription = await getUserSubscription(); 47 | setUserSubscription(existingSubscription); 48 | setLoading(false); 49 | }; 50 | getExixtingSubscription(); 51 | }, []); 52 | //Retrieve if there is any push notification subscription for the registered service worker 53 | // this use effect runs only in the first render 54 | 55 | /** 56 | * define a click handler that asks the user permission, 57 | * it uses the setSuserConsent state, to set the consent of the user 58 | * If the user denies the consent, an error is created with the setError hook 59 | */ 60 | const onClickAskUserPermission = () => { 61 | setLoading(true); 62 | setError(false); 63 | askUserPermission().then(consent => { 64 | setSuserConsent(consent); 65 | if (consent !== "granted") { 66 | setError({ 67 | name: "Consent denied", 68 | message: "You denied the consent to receive notifications", 69 | code: 0 70 | }); 71 | } 72 | setLoading(false); 73 | }); 74 | }; 75 | // 76 | 77 | /** 78 | * define a click handler that creates a push notification subscription. 79 | * Once the subscription is created, it uses the setUserSubscription hook 80 | */ 81 | const onClickSusbribeToPushNotification = () => { 82 | setLoading(true); 83 | setError(false); 84 | createNotificationSubscription() 85 | .then(function(subscrition) { 86 | setUserSubscription(subscrition); 87 | setLoading(false); 88 | }) 89 | .catch(err => { 90 | console.error("Couldn't create the notification subscription", err, "name:", err.name, "message:", err.message, "code:", err.code); 91 | setError(err); 92 | setLoading(false); 93 | }); 94 | }; 95 | 96 | /** 97 | * define a click handler that sends the push susbcribtion to the push server. 98 | * Once the subscription ics created on the server, it saves the id using the hook setPushServerSubscriptionId 99 | */ 100 | const onClickSendSubscriptionToPushServer = () => { 101 | setLoading(true); 102 | setError(false); 103 | http 104 | .post("/subscription", userSubscription) 105 | .then(function(response) { 106 | setPushServerSubscriptionId(response.id); 107 | setLoading(false); 108 | }) 109 | .catch(err => { 110 | setLoading(false); 111 | setError(err); 112 | }); 113 | }; 114 | 115 | /** 116 | * define a click handler that request the push server to send a notification, passing the id of the saved subscription 117 | */ 118 | const onClickSendNotification = async () => { 119 | setLoading(true); 120 | setError(false); 121 | await http.get(`/subscription/${pushServerSubscriptionId}`).catch(err => { 122 | setLoading(false); 123 | setError(err); 124 | }); 125 | setLoading(false); 126 | }; 127 | 128 | /** 129 | * returns all the stuff needed by a Component 130 | */ 131 | return { 132 | onClickAskUserPermission, 133 | onClickSusbribeToPushNotification, 134 | onClickSendSubscriptionToPushServer, 135 | pushServerSubscriptionId, 136 | onClickSendNotification, 137 | userConsent, 138 | pushNotificationSupported, 139 | userSubscription, 140 | error, 141 | loading 142 | }; 143 | } 144 | -------------------------------------------------------------------------------- /front-end-react/src/utils/http.js: -------------------------------------------------------------------------------- 1 | const host = process.env.NODE_ENV === "production" ? "https://push-notification-demo-server.herokuapp.com" : "http://localhost:8080"; 2 | 3 | function post(path, body) { 4 | return fetch(`${host}${path}`, { 5 | credentials: "omit", 6 | headers: { "content-type": "application/json;charset=UTF-8", "sec-fetch-mode": "cors" }, 7 | body: JSON.stringify(body), 8 | method: "POST", 9 | mode: "cors" 10 | }) 11 | .then(function(response) { 12 | return response.json(); 13 | }) 14 | .then(function(data) { 15 | return data; 16 | }); 17 | } 18 | 19 | function get(path) { 20 | return fetch(`${host}${path}`, { 21 | credentials: "omit", 22 | headers: { "content-type": "application/json;charset=UTF-8", "sec-fetch-mode": "cors" }, 23 | method: "GET", 24 | mode: "cors" 25 | }) 26 | .then(function(response) { 27 | return response.json(); 28 | }) 29 | .then(function(data) { 30 | return data; 31 | }); 32 | } 33 | 34 | const http = { 35 | post: post, 36 | get: get 37 | }; 38 | 39 | export default http; 40 | -------------------------------------------------------------------------------- /front-end/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "useBuiltIns": "usage", 7 | "corejs": "3.0.0" 8 | } 9 | ] 10 | ], 11 | "plugins": [ 12 | "@babel/plugin-syntax-dynamic-import", 13 | "@babel/plugin-proposal-class-properties" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /front-end/.browserslistrc: -------------------------------------------------------------------------------- 1 | [production staging] 2 | >5% 3 | last 2 versions 4 | Firefox ESR 5 | not ie < 11 6 | 7 | [development] 8 | last 1 chrome version 9 | last 1 firefox version 10 | last 1 edge version 11 | -------------------------------------------------------------------------------- /front-end/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "node": true 5 | }, 6 | "parserOptions": { 7 | "ecmaVersion": 6, 8 | "sourceType": "module" 9 | }, 10 | "rules": { 11 | "semi": 2 12 | } 13 | } -------------------------------------------------------------------------------- /front-end/.gitignore: -------------------------------------------------------------------------------- 1 | # dependencies 2 | node_modules 3 | 4 | # production 5 | build 6 | 7 | # misc 8 | .DS_Store 9 | 10 | npm-debug.log 11 | yarn-error.log 12 | yarn.lock 13 | .yarnclean 14 | .vscode 15 | -------------------------------------------------------------------------------- /front-end/README.md: -------------------------------------------------------------------------------- 1 | # Webpack Frontend Starterkit 2 | 3 | [![Greenkeeper badge](https://badges.greenkeeper.io/wbkd/webpack-starter.svg)](https://greenkeeper.io/) 4 | 5 | A lightweight foundation for your next webpack based frontend project. 6 | 7 | 8 | ### Installation 9 | 10 | ``` 11 | npm install 12 | ``` 13 | 14 | ### Start Dev Server 15 | 16 | ``` 17 | npm start 18 | ``` 19 | 20 | ### Build Prod Version 21 | 22 | ``` 23 | npm run build 24 | ``` 25 | 26 | ### Features: 27 | 28 | * ES6 Support via [babel](https://babeljs.io/) (v7) 29 | * SASS Support via [sass-loader](https://github.com/jtangelder/sass-loader) 30 | * Linting via [eslint-loader](https://github.com/MoOx/eslint-loader) 31 | 32 | When you run `npm run build` we use the [mini-css-extract-plugin](https://github.com/webpack-contrib/mini-css-extract-plugin) to move the css to a separate file. The css file gets included in the head of the `index.html`. 33 | -------------------------------------------------------------------------------- /front-end/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "webpack-starter", 3 | "version": "1.0.0", 4 | "description": "A light foundation for your next frontend project based on webpack.", 5 | "scripts": { 6 | "build": "NODE_ENV=production webpack --config webpack/webpack.config.prod.js --colors", 7 | "start": "PUSH_SERVER_URL=\"http://localhost:7899\" webpack-dev-server --open --config webpack/webpack.config.dev.js" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/wbkd/webpack-starter.git" 12 | }, 13 | "keywords": [ 14 | "webpack", 15 | "startkit", 16 | "frontend", 17 | "es6", 18 | "javascript", 19 | "webdev" 20 | ], 21 | "author": "webkid.io", 22 | "license": "MIT", 23 | "bugs": { 24 | "url": "https://github.com/wbkd/webpack-starter/issues" 25 | }, 26 | "devDependencies": { 27 | "@babel/core": "^7.4.0", 28 | "@babel/plugin-proposal-class-properties": "^7.4.0", 29 | "@babel/plugin-syntax-dynamic-import": "^7.2.0", 30 | "@babel/preset-env": "^7.4.2", 31 | "babel-loader": "^8.0.5", 32 | "clean-webpack-plugin": "^2.0.2", 33 | "copy-webpack-plugin": "^5.0.3", 34 | "css-loader": "^3.0.0", 35 | "eslint": "^5.16.0", 36 | "eslint-loader": "^2.1.2", 37 | "file-loader": "^4.0.0", 38 | "html-webpack-plugin": "^4.0.0-beta.5", 39 | "mini-css-extract-plugin": "^0.8.0", 40 | "node-sass": "^4.12.0", 41 | "sass-loader": "^7.1.0", 42 | "style-loader": "^0.23.1", 43 | "webpack": "^4.29.6", 44 | "webpack-cli": "^3.3.0", 45 | "webpack-dev-server": "^3.2.1", 46 | "webpack-merge": "^4.2.1" 47 | }, 48 | "dependencies": { 49 | "@babel/polyfill": "^7.4.0", 50 | "core-js": "^3.0.1" 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /front-end/public/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spyna/push-notification-demo/62733211793ee2545ea457ab7f55128f5a67105c/front-end/public/.gitkeep -------------------------------------------------------------------------------- /front-end/public/images/jason-leung-HM6TMmevbZQ-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spyna/push-notification-demo/62733211793ee2545ea457ab7f55128f5a67105c/front-end/public/images/jason-leung-HM6TMmevbZQ-unsplash.jpg -------------------------------------------------------------------------------- /front-end/public/images/repository-open-graph-template.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spyna/push-notification-demo/62733211793ee2545ea457ab7f55128f5a67105c/front-end/public/images/repository-open-graph-template.png -------------------------------------------------------------------------------- /front-end/public/new-product-jason-leung-HM6TMmevbZQ-unsplash.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Jason leung t-shirt 5 | 6 | 20 | 21 | 22 |

Congratulation! You clicked the notification.

23 | some t-shirts 24 |

This is the amazing t-shirt

25 | 26 | 27 | -------------------------------------------------------------------------------- /front-end/public/sw.js: -------------------------------------------------------------------------------- 1 | function receivePushNotification(event) { 2 | console.log("[Service Worker] Push Received."); 3 | 4 | const { image, tag, url, title, text } = event.data.json(); 5 | 6 | const options = { 7 | data: url, 8 | body: text, 9 | icon: image, 10 | vibrate: [200, 100, 200], 11 | tag: tag, 12 | image: image, 13 | badge: "https://spyna.it/icons/favicon.ico", 14 | actions: [{ action: "Detail", title: "View", icon: "https://via.placeholder.com/128/ff0000" }] 15 | }; 16 | event.waitUntil(self.registration.showNotification(title, options)); 17 | } 18 | 19 | function openPushNotification(event) { 20 | console.log("[Service Worker] Notification click Received.", event.notification.data); 21 | 22 | event.notification.close(); 23 | event.waitUntil(clients.openWindow(event.notification.data)); 24 | } 25 | 26 | self.addEventListener("push", receivePushNotification); 27 | self.addEventListener("notificationclick", openPushNotification); 28 | -------------------------------------------------------------------------------- /front-end/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 13 | 14 | 15 | 16 | Web Push notifications demo 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 |

Push notification demo

34 |

35 | Read the docs - 36 | View the source code
37 |

38 |

Push notification are supported by this browser:

39 |

User consent to push notification:

40 |
41 |

step 1 : Ask user consent to show notifications

42 | 43 |
44 |
45 |

step 2 : Susbcribe to push notification

46 |

this will create an endpoint that has to be sent to the push server


47 | 48 |
49 |
50 |

step 3 : Send the notification to the push server

51 | 52 |
53 |
54 |

step 4 : Ask the push server for a notification

55 |

in production you don't ask for notifications, The push server decide itself when to send them


56 | 57 |
58 |
59 |

User susbription:

60 |
61 |
62 | 63 | 64 | -------------------------------------------------------------------------------- /front-end/src/scripts/index.js: -------------------------------------------------------------------------------- 1 | import "../styles/index.scss"; 2 | import http from "./utils/http"; 3 | import { 4 | isPushNotificationSupported, 5 | initializePushNotifications, 6 | registerServiceWorker, 7 | getUserSubscription, 8 | createNotificationSubscription 9 | } from "./push-notifications.js"; 10 | 11 | /** 12 | * request the push server to send a notification, passing the id 13 | */ 14 | function sendNotification() { 15 | http.get(`/subscription/${subscritionId}`); 16 | } 17 | 18 | /** 19 | * updates the DOM printing the user consent and activates buttons 20 | * @param {String} userConsent 21 | */ 22 | function updateUserConsent(userConsent) { 23 | pushNotificationConsentSpan.innerHTML = userConsent; 24 | if (userConsent === "granted") { 25 | //enable push notification subscribe button 26 | susbribeToPushNotificationButton.disabled = false; 27 | } else { 28 | sendPushNotificationButton.disabled = true; 29 | susbribeToPushNotificationButton.disabled = true; 30 | } 31 | } 32 | 33 | /** 34 | * ask the user consent to receive push notification 35 | */ 36 | function askUserPermission() { 37 | initializePushNotifications().then(updateUserConsent); 38 | } 39 | 40 | /** 41 | * creates a push notification subscription, that has to be sent to the push server 42 | */ 43 | function susbribeToPushNotification() { 44 | createNotificationSubscription().then(function(subscrition) { 45 | showUserSubscription(subscrition); 46 | }); 47 | } 48 | 49 | /** 50 | * displays the subscription details in the page and enables the "send Subscription Button" 51 | * @param {PushSubscription} subscrition 52 | */ 53 | function showUserSubscription(subscrition) { 54 | userSubscrition = subscrition; 55 | document.getElementById("user-susbription").innerHTML = JSON.stringify(subscrition, null, " "); 56 | sendSubscriptionButton.disabled = false; 57 | } 58 | 59 | /** 60 | * sends the push susbcribtion to the push server 61 | */ 62 | function sendSubscriptionToPushServer() { 63 | http.post("/subscription", userSubscrition).then(function(response) { 64 | subscritionId = response.id; 65 | sendPushNotificationButton.disabled = false; 66 | }); 67 | } 68 | 69 | 70 | let userSubscrition; 71 | let subscritionId; 72 | 73 | //checks if the browser supports push notification and service workers 74 | const pushNotificationSuported = isPushNotificationSupported(); 75 | 76 | const pushNotificationConsentSpan = document.getElementById("push-notification-consent"); 77 | const pushNotificationSupportedSpan = document.getElementById("push-notification-supported"); 78 | pushNotificationSupportedSpan.innerHTML = pushNotificationSuported; 79 | 80 | const askUserPemissionButton = document.getElementById("ask-user-permission-button"); 81 | askUserPemissionButton.addEventListener("click", askUserPermission); 82 | 83 | const susbribeToPushNotificationButton = document.getElementById("create-notification-subscription-button"); 84 | susbribeToPushNotificationButton.addEventListener("click", susbribeToPushNotification); 85 | 86 | const sendSubscriptionButton = document.getElementById("send-subscription-button"); 87 | sendSubscriptionButton.addEventListener("click", sendSubscriptionToPushServer); 88 | 89 | const sendPushNotificationButton = document.getElementById("send-push-notification-button"); 90 | sendPushNotificationButton.addEventListener("click", sendNotification); 91 | 92 | if (pushNotificationSuported) { 93 | updateUserConsent(Notification.permission); 94 | askUserPemissionButton.disabled = false; 95 | // register the service worker: file "sw.js" in the root of our project 96 | registerServiceWorker(); 97 | getUserSubscription().then(function(subscrition) { 98 | if (subscrition) { 99 | showUserSubscription(subscrition); 100 | } 101 | }); 102 | } -------------------------------------------------------------------------------- /front-end/src/scripts/push-notifications.js: -------------------------------------------------------------------------------- 1 | const pushServerPublicKey = "BIN2Jc5Vmkmy-S3AUrcMlpKxJpLeVRAfu9WBqUbJ70SJOCWGCGXKY-Xzyh7HDr6KbRDGYHjqZ06OcS3BjD7uAm8"; 2 | 3 | /** 4 | * checks if Push notification and service workers are supported by your browser 5 | */ 6 | function isPushNotificationSupported() { 7 | return "serviceWorker" in navigator && "PushManager" in window; 8 | } 9 | 10 | /** 11 | * asks user consent to receive push notifications and returns the response of the user, one of granted, default, denied 12 | */ 13 | function initializePushNotifications() { 14 | // request user grant to show notification 15 | return Notification.requestPermission(function(result) { 16 | return result; 17 | }); 18 | } 19 | /** 20 | * shows a notification 21 | */ 22 | function sendNotification() { 23 | const img = "/images/jason-leung-HM6TMmevbZQ-unsplash.jpg"; 24 | const text = "Take a look at this brand new t-shirt!"; 25 | const title = "New Product Available"; 26 | const options = { 27 | body: text, 28 | icon: "/images/jason-leung-HM6TMmevbZQ-unsplash.jpg", 29 | vibrate: [200, 100, 200], 30 | tag: "new-product", 31 | image: img, 32 | badge: "https://spyna.it/icons/android-icon-192x192.png", 33 | actions: [{ action: "Detail", title: "View", icon: "https://via.placeholder.com/128/ff0000" }] 34 | }; 35 | navigator.serviceWorker.ready.then(function(serviceWorker) { 36 | serviceWorker.showNotification(title, options); 37 | }); 38 | } 39 | 40 | /** 41 | * 42 | */ 43 | function registerServiceWorker() { 44 | navigator.serviceWorker.register("/sw.js").then(function(swRegistration) { 45 | //you can do something with the service wrker registration (swRegistration) 46 | }); 47 | } 48 | 49 | /** 50 | * 51 | * using the registered service worker creates a push notification subscription and returns it 52 | * 53 | */ 54 | function createNotificationSubscription() { 55 | //wait for service worker installation to be ready, and then 56 | return navigator.serviceWorker.ready.then(function(serviceWorker) { 57 | // subscribe and return the subscription 58 | return serviceWorker.pushManager 59 | .subscribe({ 60 | userVisibleOnly: true, 61 | applicationServerKey: pushServerPublicKey 62 | }) 63 | .then(function(subscription) { 64 | console.log("User is subscribed.", subscription); 65 | return subscription; 66 | }); 67 | }); 68 | } 69 | 70 | /** 71 | * returns the subscription if present or nothing 72 | */ 73 | function getUserSubscription() { 74 | //wait for service worker installation to be ready, and then 75 | return navigator.serviceWorker.ready 76 | .then(function(serviceWorker) { 77 | return serviceWorker.pushManager.getSubscription(); 78 | }) 79 | .then(function(pushSubscription) { 80 | return pushSubscription; 81 | }); 82 | } 83 | 84 | export { 85 | isPushNotificationSupported, 86 | initializePushNotifications, 87 | registerServiceWorker, 88 | sendNotification, 89 | createNotificationSubscription, 90 | getUserSubscription 91 | }; 92 | -------------------------------------------------------------------------------- /front-end/src/scripts/utils/http.js: -------------------------------------------------------------------------------- 1 | const host = process.env.PUSH_SERVER_URL; 2 | 3 | function post(path, body) { 4 | return fetch(`${host}${path}`, { 5 | credentials: "omit", 6 | headers: { "content-type": "application/json;charset=UTF-8", "sec-fetch-mode": "cors" }, 7 | body: JSON.stringify(body), 8 | method: "POST", 9 | mode: "cors" 10 | }) 11 | .then(function(response) { 12 | return response.json(); 13 | }) 14 | .then(function(data) { 15 | return data; 16 | }); 17 | } 18 | 19 | function get(path) { 20 | return fetch(`${host}${path}`, { 21 | credentials: "omit", 22 | headers: { "content-type": "application/json;charset=UTF-8", "sec-fetch-mode": "cors" }, 23 | method: "GET", 24 | mode: "cors" 25 | }) 26 | .then(function(response) { 27 | return response.json(); 28 | }) 29 | .then(function(data) { 30 | return data; 31 | }); 32 | } 33 | 34 | const http = { 35 | post: post, 36 | get: get 37 | }; 38 | 39 | export default http; 40 | -------------------------------------------------------------------------------- /front-end/src/styles/index.scss: -------------------------------------------------------------------------------- 1 | body { 2 | width: 360px; 3 | max-width: 100%; 4 | margin: auto; 5 | } 6 | 7 | button { 8 | background-color: #4caf50; /* Green */ 9 | border: none; 10 | color: white; 11 | padding: 10px 22px; 12 | text-align: center; 13 | text-decoration: none; 14 | display: inline-block; 15 | font-size: 1.2rem; 16 | border-radius: 5px; 17 | margin: 1px; 18 | cursor: pointer; 19 | border: 1px solid #4caf50; 20 | } 21 | 22 | button:hover, 23 | button:active { 24 | border: 1px solid #ccc; 25 | } 26 | 27 | button:disabled { 28 | background-color: #ddd; 29 | border: 1px solid #ccc; 30 | cursor: not-allowed; 31 | } 32 | 33 | pre, 34 | code { 35 | border: 1px solid #ccc; 36 | padding: 5px; 37 | overflow-x: auto; 38 | white-space: pre-wrap; 39 | white-space: -moz-pre-wrap; 40 | white-space: -pre-wrap; 41 | white-space: -o-pre-wrap; 42 | word-wrap: break-word; 43 | max-width: 100%; 44 | word-wrap: break-word; 45 | } 46 | -------------------------------------------------------------------------------- /front-end/webpack/webpack.common.js: -------------------------------------------------------------------------------- 1 | const Path = require('path'); 2 | const CleanWebpackPlugin = require('clean-webpack-plugin'); 3 | const CopyWebpackPlugin = require('copy-webpack-plugin'); 4 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 5 | 6 | module.exports = { 7 | entry: { 8 | app: Path.resolve(__dirname, '../src/scripts/index.js') 9 | }, 10 | output: { 11 | path: Path.join(__dirname, '../build'), 12 | filename: 'js/[name].js' 13 | }, 14 | optimization: { 15 | splitChunks: { 16 | chunks: 'all', 17 | name: false 18 | } 19 | }, 20 | plugins: [ 21 | new CleanWebpackPlugin(), 22 | new CopyWebpackPlugin([ 23 | { from: Path.resolve(__dirname, '../public'), to: '' } 24 | ]), 25 | new HtmlWebpackPlugin({ 26 | template: Path.resolve(__dirname, '../src/index.html') 27 | }) 28 | ], 29 | resolve: { 30 | alias: { 31 | '~': Path.resolve(__dirname, '../src') 32 | } 33 | }, 34 | module: { 35 | rules: [ 36 | { 37 | test: /\.mjs$/, 38 | include: /node_modules/, 39 | type: 'javascript/auto' 40 | }, 41 | { 42 | test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/, 43 | use: { 44 | loader: 'file-loader', 45 | options: { 46 | name: '[path][name].[ext]' 47 | } 48 | } 49 | }, 50 | ] 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /front-end/webpack/webpack.config.dev.js: -------------------------------------------------------------------------------- 1 | const Path = require('path'); 2 | const Webpack = require('webpack'); 3 | const merge = require('webpack-merge'); 4 | const common = require('./webpack.common.js'); 5 | 6 | 7 | module.exports = merge(common, { 8 | mode: 'development', 9 | devtool: 'cheap-eval-source-map', 10 | output: { 11 | chunkFilename: 'js/[name].chunk.js' 12 | }, 13 | devServer: { 14 | inline: true, 15 | port:9000 16 | }, 17 | plugins: [ 18 | new Webpack.DefinePlugin({ 19 | 'process.env.NODE_ENV': JSON.stringify('development'), 20 | 'process.env.PUSH_SERVER_URL': JSON.stringify('http://localhost:8080'), 21 | }) 22 | ], 23 | module: { 24 | rules: [ 25 | { 26 | test: /\.(js)$/, 27 | include: Path.resolve(__dirname, '../src'), 28 | enforce: 'pre', 29 | loader: 'eslint-loader', 30 | options: { 31 | emitWarning: true, 32 | } 33 | }, 34 | { 35 | test: /\.(js)$/, 36 | include: Path.resolve(__dirname, '../src'), 37 | loader: 'babel-loader' 38 | }, 39 | { 40 | test: /\.s?css$/i, 41 | use: ['style-loader', 'css-loader?sourceMap=true', 'sass-loader'] 42 | } 43 | ] 44 | } 45 | }); 46 | -------------------------------------------------------------------------------- /front-end/webpack/webpack.config.prod.js: -------------------------------------------------------------------------------- 1 | const Path = require('path'); 2 | const Webpack = require('webpack'); 3 | const merge = require('webpack-merge'); 4 | const MiniCssExtractPlugin = require('mini-css-extract-plugin'); 5 | const common = require('./webpack.common.js'); 6 | 7 | module.exports = merge(common, { 8 | mode: 'production', 9 | devtool: 'source-map', 10 | stats: 'errors-only', 11 | bail: true, 12 | output: { 13 | filename: 'js/[name].[chunkhash:8].js', 14 | chunkFilename: 'js/[name].[chunkhash:8].chunk.js' 15 | }, 16 | plugins: [ 17 | new Webpack.DefinePlugin({ 18 | 'process.env.NODE_ENV': JSON.stringify('production'), 19 | 'process.env.PUSH_SERVER_URL': JSON.stringify('https://push-notification-demo-server.herokuapp.com'), 20 | }), 21 | new Webpack.optimize.ModuleConcatenationPlugin(), 22 | new MiniCssExtractPlugin({ 23 | filename: 'bundle.css' 24 | }) 25 | ], 26 | module: { 27 | rules: [ 28 | { 29 | test: /\.(js)$/, 30 | exclude: /node_modules/, 31 | use: 'babel-loader' 32 | }, 33 | { 34 | test: /\.s?css/i, 35 | use : [ 36 | MiniCssExtractPlugin.loader, 37 | 'css-loader', 38 | 'sass-loader' 39 | ] 40 | } 41 | ] 42 | } 43 | }); 44 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "push-notification-demo", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "license": "MIT", 6 | "scripts": { 7 | "start": "cd ./back-end && npm install && node ./src/server", 8 | "deploy:front-end": "cd front-end && npm install && npm run build", 9 | "deploy:front-end-react": "cd front-end-react && npm install && npm run build" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /push-notification.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Spyna/push-notification-demo/62733211793ee2545ea457ab7f55128f5a67105c/push-notification.jpg --------------------------------------------------------------------------------