{"id":27213282,"url":"https://github.com/theanam/pushkit","last_synced_at":"2025-04-10T02:21:36.801Z","repository":{"id":42804697,"uuid":"266236486","full_name":"theanam/pushkit","owner":"theanam","description":"All the required components to set up independent web push notifications 🎈","archived":false,"fork":false,"pushed_at":"2023-01-06T08:20:45.000Z","size":492,"stargazers_count":62,"open_issues_count":10,"forks_count":7,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-18T12:34:45.024Z","etag":null,"topics":["notifications","progressive-web-app","push-notifications","pwa","service-worker","web-push","web-push-notification"],"latest_commit_sha":null,"homepage":"https://npm.im/pushkit","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/theanam.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-05-23T00:53:19.000Z","updated_at":"2024-09-04T18:04:29.000Z","dependencies_parsed_at":"2023-02-05T17:01:31.750Z","dependency_job_id":null,"html_url":"https://github.com/theanam/pushkit","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/theanam%2Fpushkit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/theanam%2Fpushkit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/theanam%2Fpushkit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/theanam%2Fpushkit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/theanam","download_url":"https://codeload.github.com/theanam/pushkit/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248143120,"owners_count":21054709,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["notifications","progressive-web-app","push-notifications","pwa","service-worker","web-push","web-push-notification"],"created_at":"2025-04-10T02:21:36.210Z","updated_at":"2025-04-10T02:21:36.785Z","avatar_url":"https://github.com/theanam.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# A complete toolkit for setting up independent Web Push notification.\n\nEverything you need to enable Web Push Notification in your Node.JS web application. Uses the browser's delivery channel to send push notification(Free of cost), which means no extra third-party service (except for the browser's own delivery channel). Works with Progressive Web Apps (PWA). \n\n## 🌍 [Check the client example](https://theanam.github.io/pushkit)\n\n## 🚀 [Check the server example and tester](https://pushkit.herokuapp.com/)\n\n## Generate your VAPID keys first: \nBefore starting the setup, you need to create own own VAPID key pair. This is extremely easy. There are many ways to do it:\n\n1. Generate it from [Pushkit Server example and Tester](https://pushkit.herokuapp.com/)\n2. Generate online from [this site](https://web-push-codelab.glitch.me/)\n3. Using this tool: [web-push](https://www.npmjs.com/package/web-push)\n\nOnce you have your VAPID key pair (Public and Private key). You need to store them carefully. you have to use them to setup your web push implementation in server and client.\n\n## Installation\nThis package contains both the client and server tools packaged in their own module loading format. To install the package run this:\n```shell\nyarn add pushkit\n```\n\n## Client Setup: \nPushkit works with the Service Worker API. It's journey starts when the service worker gets registered. Below is an example code that sets up pushkit with the service worker registration and sends the Push Registration information (URL and key to send push notification payload) to the server using the fetch API. You can use it like this, or use a different method to preserve the Push Registration object. (Which is Serializable). Once a browser generates this, it can be used to send push notification to that browser.\n\n```js\nimport {PushKit} from \"pushkit/client\";\n// create an instance\nlet pkInstance = new PushKit(\"PUBLIC_VAPID_KEY\", true);\n// register service worker\nfunction startPushReg(){\n    navigator.serviceWorker.register(\"./sw.js\").then(swreg=\u003e{\n        // start push registration after service worker registration\n        pkInstance.handleRegistration(swreg).then(pushreg=\u003e{\n            // Once push registration is done\n            // Send the registration data to the server\n            // You can implement this part in your convenient way\n            // The below example uses `fetch` API to do it.\n            let regData = JSON.stringify(pushreg);\n            fetch(\"/reg\", {\n                method  : \"POST\",\n                body    : regData,\n                headers : {\n                    \"content-type\":\"application/json\"\n                }\n            });\n        });\n    });\n}\n// Run this after at least one user interaction.\n// e.g: a button click. Otherwise there's a chance that it will fail.\ndocument.querySelector(\".subscribe\").addEventListener(\"click\", startPushReg);\n// You can hide this button using `pkInstance.granted` property. granted === already set up\nif(pkInstance.granted){\n    document.querySelector(\".subscribe\").style.display = \"none\";\n}\n```\nThe above code creates a `PushKit` Instance, The constructor takes two arguments, The first argument is required. The second argument is false by default, setting it true will generate logs in console.\n\n```js\nlet _pk = new PushKit(\"\u003cPUBLIC_VAPID_KEY\u003e\", [verbose = false]);\n```\n\nThe registration of service worker is not included in the plugin itself. This is to avoid getting in the user's way. Besides it's simple. The method `navigator.serviceWorker.register` takes the service worker file (more in this later) and returns a promise. This promise is resolved with a `ServiceWorkerRegistration` object. \n\n```js\npushKitInstance.handleRegistration(ServiceWorkerRegistration)\n```\nthis also returns a promise that resolves either with a `null` if the user denies, or push is not supported or there's any error. Or the push registration.\n\nThe registration object is **different for every user and every browser**. You have to send this registration object to the server and store it there for that user. In the example, `fetch` was used to do it. This registration object will be used to send push notification to that user. [See this section](#sending-push-notification-sender.send)\n\n#### Pushkit Instance\nOnce created, a PushKit instance has these following properties:\n\n|Property|Type|Description|\n|--------|----|-----------|\n|granted|Boolean|Determines if push permission is already granted.\u003cbr\u003e Can be used for hiding prompts|\n|handleRegistration|Function|Helper function to handle push registration|\n|reg|`serviceWorkerRegistration`\u003cbr\u003e Object|The PushRegistration object.\u003cbr\u003e Available after calling `handleRegistration`|\n|sub|`PushSubscription`\u003cbr\u003e Object| The pushSubscription object.\u003cbr\u003e Available after calling `handleRegistration`|\n|subscribed|Boolean|Determines if the user is subscribed.\u003cbr\u003e Available after calling `handleRegistration`|\n|supported|Boolean|Determines if push notification is supported by the browser|\n\n### Using from a CDN:\n*If you are not using a module bundler, or you'd like to use a CDN for the frontend part instead, you can manually add the script tag in your HTML file like this:*\n\n```html\n\u003cscript src=\"https://unpkg.com/pushkit@3.2.1/client/dist/index.js\"\u003e\u003c/script\u003e\n```\n\u003e If you chose to include the JavaScript file in your HTML, instead of calling `new PushKit()` you have to call `new pushKit.PushKit()`. Every other frontend API are the same.\n\n## Server Setup\nTo set up the server, install the `pushkit` package on the server as well and then it can be imported like this:\n\n```js\nconst createSender  = require(\"pushkit/server\");\nlet sender     = createSender({\n    publicKey  : \"PUBLIC_VAPID_KEY\",\n    privateKey : \"PRIVATE_VAPID_KEY\"\n},\"your@email.address\");\n```\nThe Email Address is requred for web push API. Once instance of sender is enough for one set of vapid key (one application).\n### Sending Push Notification from server `sender.send`:\n ```js\n sender.send(pushRegistrationObject, title, [config]);\n```\n```js\nlet config = {\n    body: \"Street dogs don't want anything more than love and shelter.\"\n}\n// Here, the `pushRegistrationObject` is the object sent from the client that was stored on the server.\n// Make sure to parse the pushRegistrationObject from JSON string\nsender.send(pushRegistrationObject,\"Adopt a street dog today!\", config);\n```\n\n## Configuring Push Behavior:\nThe `config` object can be used to customize the behaviour of the push notification. These can be sent from the server as per-message basis or can be set in the service worker binding as default. Settings sent from server will always get precedence over default settings.\n\n| property | Data Type | description |\n|----------|-----------|-------------|\n|body| String|Text to show in the notification body| \n|badge|String|URL of an image to be used as badge,\u003cbr\u003e mostly in mobile devices|\n|dir|String|Useful if you want to determine the text direction,\u003cbr\u003e default is `auto`. \u003cbr\u003eIt can be set to `ltr`, or `rtl`|\n|icon|String|URL of an image to be used as the \u003cbr\u003e icon of the notification|\n|image|String|URL of an image to be showin in the\u003cbr\u003e notification body (for notification with image content)|\n|lang|String|A [BCP47](https://tools.ietf.org/html/bcp47) Language code\u003cbr\u003e for the notification language|\n|renotify|Boolean|Used with the `tag` property,\u003cbr\u003e if set to will renotify for all the \u003cbr\u003enotification on the same tag|\n|requireInteraction|Boolean|Determine if the notification REQUIRES user\u003cbr\u003e to interact before it disappears, use it responsibly|\n|silent|Boolean|When set to true, notifications will\u003cbr\u003e not play notification sound or vibrate|\n|tag|String|Useful when you want to group notification\u003cbr\u003e on the same topic. e.g: chat from the\u003cbr\u003e same person, just set a common tag|\n|timestamp|Number|Determines when the notification is created,\u003cbr\u003e useful for figuring out how long it took to deliver|\n|vibrate|Array of Number|Determines a vibration pattern to use,\u003cbr\u003e each number represents milleseconds \u003cbr\u003e of vibration e.g: [200,100,100]|\n\nA more detailed documentation on the config options are here: \u003chttps://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification\u003e\n\n## Setting up the service worker\nThe last piece of puzzle is to set up a service worker. Now if you are using a boilerplate/generator there's a chance that you already have a service worker. A service worker is a JavaScript file that gets loaded in the client in such a way, that it can still remain active even after you've left the web application. That's why Service workers can receive push notifications. In the client setup section we used a service worker file called `sw.js`, the URL should be accessible from the browser and have to be on the same domain (for security reasons). \n\nIf you don't have a service worker, create one, if you have one, open it, and import the piece of code required to initiate the service Worker. You can either use it from CDN, or download the `worker/binding.js` file from the repository and import it. \n```js\nimportScripts(\"https://unpkg.com/pushkit@3.2.1/worker/binding.js\"); \n```\nThen you can attach the pushkit listeners with your service worker like this:\n```js\nattachPushKit(self, pushConfig, [defaultTitle = \"\", defaultURL = \"\",customClickHandler = null,  verbose = false]);\n```\n|Argument|Required|Default|Description|\n|--------|--------|-------|-----------|\n|self|true|n/a|The service worker context\u003cbr\u003ethe value will always be `self`|\n|pushConfig|false|null|Default behavior of push messages. \u003cbr\u003e See [Configuring Push behavior](#configuring-push-behavior) |\n|defaultTitle|false|\"\"|Default Title for Push Messages|\n|defaultURL|false|\"\"|Default URL to open or focus \u003cbr\u003e when push message is clicked\u003cbr\u003e this Will not work if the default click \u003cbr\u003ehandler is changed|\n|customClickHandler|false|null|If you want to change the default \u003cbr\u003e click behavior of the push click event. Takes \u003cbr\u003e a function and passes the `event` object.|\n|verbose|false|false|If set to true, console logs\u003cbr\u003e will be generated|\n\nSample Use in service worker: \n\n```js\nimportScripts(\"https://unpkg.com/pushkit@3.2.1/worker/binding.js\"); \nvar pushConfig = {\n    icon  : \"ICON_URL\",\n    badge : \"BADGE_URL\"\n}\nattachPushKit(self, pushConfig);\n```\nThe `PushConfig` object can have any properties from the [Configuring Push Behavior](#configuring-push-behavior)  section above.If the same properties are also sent from the server, server values will get precedence. You can read the full documentation of the available config options here: \u003chttps://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification\u003e\n\n## Using a different backend:\n\nIf your backend is written in a different language, and you want to use Pushkit in the frontend only. You can definitely do that. Pushkit only knows `JSON` push data. You have to send *JSON string* as push data in the following format: \n\n```json\n{\n    \"title\"   : \"Push Notification Title\",\n    \"url\"     : \"https://where-to-go\",\n    \"config\"  : {\n        \"body\": \"Push notification body\"\n    }\n}\n```\nThis config here can have any value from [here](#configuring-push-behavior), Pushkit will be able to parse this and work without any issues.\n\n\n\u003e One more thing, Make sure your application is served from a secure origin `https`. otherwise push notification will not work.\n\n**** \nThis tool is released under the MIT License. Feel free to contribute.\n\n\nMade with 💙 and JavaScript\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftheanam%2Fpushkit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftheanam%2Fpushkit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftheanam%2Fpushkit/lists"}