homeresume
 
   

Push notifications with Firebase

May 29, 2022

Push notifications are a great alternative to email notifications, there is no need for a verification step, UX is improved and user engagement with the app is increased.

Requirements for the push notifications

  • Created Firebase project
  • Project ID, can be found on Project settings General tab
  • Server key for sending the push notifications (used on the back-end)
  • Public Vapid key, can be found on Project settings Cloud Messaging Web Push certificates (used on the front-end)
  • Firebase configuration, can be found on Project settings General Your apps
  • Firebase messaging service worker
  • HTTPS connection (localhost for local development)
  • firebase package installed

Helper functions

getToken

  • generates unique token for the browser or gets already generated token
  • requests permission for receiving push notifications
  • triggers the Firebase messaging service worker

If the user blocks the push notifications, FirebaseError error with code messaging/permission-blocked is thrown. If the user's browser doesn't support the APIs required to use the Firebase SDK, FirebaseError error with code messaging/unsupported-browser is thrown. The access token is invalidated when a user manually blocks the notifications in the browser settings.

isSupported

  • checks if all required APIs for push notifications are supported
  • returns Promise<boolean>

It should be used in useEffect hooks.

import { isSupported } from 'firebase/messaging';
// ...
useEffect(() => {
isSupported()
.then((isAvailable) => {
if (isAvailable) {
// ...
}
})
.catch(console.error);
}, []);
// ...

initializeApp

  • should be called before the app starts
import { initializeApp } from 'firebase/app';
import { getMessaging, getToken } from 'firebase/messaging';
import { firebaseConfig } from 'constants/config';
export const initializeFirebase = () => initializeApp(firebaseConfig);
export const getTokenForPushNotifications = async () => {
const messaging = getMessaging();
const token = await getToken(messaging, {
vapidKey: process.env.NEXT_PUBLIC_VAPID_KEY,
});
return token;
}

Firebase messaging service worker

The following service worker should be registered for handling background notifications. Custom notificationclick handler should be implemented before importing firebase libraries, the below implementation opens a new window with the defined URL if it is not already open. Firebase automatically checks for service workers at /firebase-messaging-sw.js so it should be publicly available.

// /firebase-messaging-sw.js
/* eslint-disable no-unused-vars */
self.addEventListener("notificationclick", (event) => {
event.notification.close();
const DEFAULT_URL = "<URL>";
const url =
event.notification?.data?.FCM_MSG?.notification?.click_action ||
DEFAULT_URL;
event.waitUntil(
clients.matchAll({ type: "window" }).then((clientsArray) => {
const hadWindowToFocus = clientsArray.some((windowClient) =>
windowClient.url === url ? (windowClient.focus(), true) : false
);
if (!hadWindowToFocus)
clients
.openWindow(url)
.then((windowClient) => (windowClient ? windowClient.focus() : null));
})
);
});
let messaging = null;
try {
if (typeof importScripts === "function") {
importScripts("https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js");
importScripts(
"https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"
);
firebase.initializeApp({
apiKey: "xxxxxx",
authDomain: "xxxxxx",
projectId: "xxxxxx",
storageBucket: "xxxxxx",
messagingSenderId: "xxxxxx",
appId: "xxxxxx",
measurementId: "xxxxxx",
});
messaging = firebase.messaging();
}
} catch (error) {
console.error(error);
}

Server keys

The server key for API v1 can be derived from the service account key JSON file, in that case, the JSON file should be encoded and stored in the environment variable to prevent exposing credentials in the repository codebase. The service account key JSON file can be downloaded by clicking Generate new private key on Project settings Service accounts tab. The server key for the legacy API can be found on Project settings Cloud Messaging Cloud Messaging API (Legacy), if it is enabled.

import * as serviceAccountKey from './serviceAccountKey.json';
const encodedServiceAccountKey = Buffer.from(
JSON.stringify(serviceAccountKey),
).toString('base64');
process.env.SERVICE_ACCOUNT_KEY = encodedServiceAccountKey;
import 'dotenv/config';
import * as googleAuth from 'google-auth-library';
(async () => {
const serviceAccountKeyEncoded = process.env.SERVICE_ACCOUNT_KEY;
const serviceAccountKeyDecoded = JSON.parse(
Buffer.from(serviceAccountKeyEncoded, 'base64').toString('ascii'),
);
const jwt = new googleAuth.JWT(
serviceAccountKeyDecoded.client_email,
null,
serviceAccountKeyDecoded.private_key,
['https://www.googleapis.com/auth/firebase.messaging'],
null,
);
const tokens = await jwt.authorize();
const authorizationHeader = `Bearer ${tokens.access_token}`;
console.log(authorizationHeader);
})();

Manually sending the push notification

Icon URL should be covered with HTTPS so the icon can be properly shown in the notification.

  • legacy
curl --location --request POST 'https://fcm.googleapis.com/fcm/send' \
--header 'Authorization: key=<SERVER_KEY>' \
--header 'Content-Type: application/json' \
--data-raw '{
"notification": {
"title": "Push notifications with Firebase",
"body": "Push notifications with Firebase body",
"click_action": "http://localhost:3000",
"icon": "https://picsum.photos/200"
},
"to": "<TOKEN>"
}'

The response contains success key with 1 value when the push notification is successfully sent. The response contains failure key with 1 value when sending the push notification failed, in this case, results key is an array with error objects, some of the error names are InvalidRegistration and NotRegistered.

  • API v1
curl --location --request POST 'https://fcm.googleapis.com/v1/projects/<PROJECT_ID>/messages:send' \
--header 'Authorization: Bearer <TOKEN_DERIVED_FROM_SERVICE_ACCOUNT_KEY>' \
--header 'Content-Type: application/json' \
--data-raw '{
"message": {
"notification": {
"title": "Push notifications with Firebase",
"body": "Push notifications with Firebase body"
},
"webpush": {
"fcmOptions": {
"link": "http://localhost:3000"
},
"notification": {
"icon": "https://picsum.photos/200"
}
},
"token": "<TOKEN>"
}
}'

Successful response return JSON with name key which presents the notification id in the format projects/{project_id}/messages/{message_id}. Error with code 400 is thrown when request body is not valid. Error with code 401 is thrown when the derived token is expired.

State management with Next.js and React

May 15, 2022

Global state can be useful when component share some common parts. Also some parts can stay persistent (in local storage) and be used in the next user's session. React provides native way to handle state management using context with the hooks.

Usage

// ...
import { useAppContext } from "context";
import { UPDATE_FEATURE_ACTIVATION } from "context/constants";
export function CustomComponent() {
const { state, dispatch } = useAppContext();
// get value from the store
console.log(state.isFeatureActivated);
// dispatch action to change the state
dispatch({ type: UPDATE_FEATURE_ACTIVATION, payload: { isFeatureActivated: true } });
// ...
}

Context setup

// context/index.jsx
import PropTypes from "prop-types";
import React, {
createContext,
useContext,
useEffect,
useMemo,
useReducer,
} from "react";
import { getItem, setItem, STATE_KEY } from "utils/local-storage";
import { INITIALIZE_STORE } from "./constants";
import { appReducer, initialState } from "./reducer";
const appContext = createContext(initialState);
export function AppWrapper({ children }) {
const [state, dispatch] = useReducer(appReducer, initialState);
const contextValue = useMemo(() => {
return { state, dispatch };
}, [state, dispatch]);
useEffect(() => {
const stateItem = getItem(STATE_KEY);
if (!stateItem) return;
const parsedState = JSON.parse(stateItem);
const updatedState = {
...initialState,
// persistent state
isFeatureActivated: parsedState.isFeatureActivated,
};
dispatch({
type: INITIALIZE_STORE,
payload: updatedState,
});
}, []);
useEffect(() => {
if (state !== initialState) {
setItem(STATE_KEY, JSON.stringify(state));
}
}, [state]);
return (
<appContext.Provider value={contextValue}>{children}</appContext.Provider>
);
}
AppWrapper.propTypes = {
children: PropTypes.oneOfType([PropTypes.array, PropTypes.object]).isRequired,
};
export function useAppContext() {
return useContext(appContext);
}

Reducer with actions

// context/reducer.js
import { INITIALIZE_STORE, UPDATE_FEATURE_ACTIVATION } from "./constants";
export const initialState = {
isFeatureActivated: false,
};
export const appReducer = (state, action) => {
switch (action.type) {
case INITIALIZE_STORE: {
return action.payload;
}
case UPDATE_FEATURE_ACTIVATION: {
return {
...state,
isFeatureActivated: action.payload.isFeatureActivated,
};
}
default:
return state;
}
};

Wrapper around the app

// _app.jsx
import { AppWrapper } from "context";
function App({ Component, pageProps }) {
// ...
return (
<AppWrapper>
<Component {...pageProps} />
</AppWrapper>
);
}

Constants

// context/constants.js
export const INITIALIZE_STORE = "INITIALIZE_STORE";
export const UPDATE_FEATURE_ACTIVATION = "UPDATE_FEATURE_ACTIVATION";

Integrating Next.js app with Google analytics 4

February 6, 2022

Google analytics helps get more insights into app usage.

Prerequisites

  • Google analytics product is already set up, tracking ID is needed
  • Next.js app should be bootstrapped
  • react-ga4 package is installed

Analytics initialization

Analytics should be initialized inside pages/_app.js file.

import ReactGA from "react-ga4";
// ...
if (isEnvironment("production")) {
ReactGA.initialize(ANALYTICS_TRACKING_ID);
}

Tracking events (clicks, e.g.)

// ...
export function trackEvent(category, label, action = "click") {
if (isEnvironment("production")) {
ReactGA.event({
action,
category,
label,
});
}
}
// ...
<Button onClick={() => trackEvent("category", "label")}>
2021

 

© 2022