Skip to content

Commit

Permalink
docs: fixed regex for parsing base64String, and updated subscribeToPu…
Browse files Browse the repository at this point in the history
…sh function. (vercel#73940)

### What?

Change 1:
At line 107, the regex code is now fixed to replace all "-" with "+",
which wasn't as expected with previous code, window.atob() would throw
an error saying the string is not encoded properly. The variable base64
will now have a URL safe base64String.

Change 2:
At line 177 and 178, the function is now updated to call the server
action subscribeUser() with a serialized object instead of a
PushSubscription object, as server actions can only be called with
serialized objects.

### Why?

I followed to docs to setup a PWA project with next, and I encountered
issues with the code mentioned in the documentation.

### How?

The fixed code snippets will work as expected, and anyone following the
docs later can find them helpful.

---------

Co-authored-by: Lee Robinson <[email protected]>
Co-authored-by: JJ Kasper <[email protected]>
  • Loading branch information
3 people authored Dec 17, 2024
1 parent 5a24406 commit 12a03ab
Showing 1 changed file with 3 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,7 @@ import { subscribeUser, unsubscribeUser, sendNotification } from './actions'

function urlBase64ToUint8Array(base64String: string) {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
const base64 = (base64String + padding)
.replace(/\\-/g, '+')
.replace(/_/g, '/')
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')

const rawData = window.atob(base64)
const outputArray = new Uint8Array(rawData.length)
Expand Down Expand Up @@ -174,7 +172,8 @@ function PushNotificationManager() {
),
})
setSubscription(sub)
await subscribeUser(sub)
const serializedSub = JSON.parse(JSON.stringify(sub))
await subscribeUser(serializedSub)
}

async function unsubscribeFromPush() {
Expand Down

0 comments on commit 12a03ab

Please sign in to comment.