/moesif-next-js-example

an example integrating Moesif into an app built on next.js

Primary LanguageJavaScript

Moesif Next.js Example

Next is a popular React framework that gives you building blocks to create web applications. It primarily focus on building web UI, but it also supports building APIs on the sever side as well.

Moesif is an API analytics platform.

moesif-nodejs is a middleware for SERVER that makes integration with Moesif easy for Nodejs based APIs including APIs that are build in Next.

moesif-browser-js is a BROWSER only libraries that tracks user actions and user profiles so that you can tie those actions to the APIs. moesif-browser-js only runs in the browser, since next.js support server side rendering, there are some things you need to do to ensure only import moesif-browser-js on client side.

This example is a Next.js application with Moesif's API analytics and monitoring integrated.

How to run this example for server side:

  1. Install all dependencies:
npm install
  1. Add your Moesif Application Id to middleware/moesifMiddleware.js

Your Moesif Application Id can be found in the Moesif Portal. After signing up for a Moesif account, your Moesif Application Id will be displayed during the onboarding steps.

You can always find your Moesif Application Id at any time by logging into the Moesif Portal, click on the bottom-left menu, and clicking Installation.

const moesifOptions = {
  applicationId:
    process.env.MOESIF_APPLICATION_ID || "Your Moesif Application Id",
  ...
}

Note: Next.js currently does not support global middlewares out of the box. This example follows a pattern of creating a middleware and wrapping each route with a HOF to insert the middleware. Each route in this example needs to be wrapped by withMiddleware in order to be detected by the Moesif app. See the api/goodbye endpoint for how to chain additional middlewares.

  1. Run the example, it will listen on port 3000.
npm run dev
  1. Send some requests to some of the routes and verify that the API calls are captured in your Moesif account.
curl --location --request GET 'http://localhost:3000/api/goodbye/' \
--header 'Content-Type: application/json' \
--header 'my-user-id: my-user-id' \
--header 'my-company-id: my-company-id'

Client Side user tracking

For client side, moesif-browser-js can not be used in server side rendering. It must be loaded and inited on the browser side. You can do this by using dynamic import, and do it in useEffect or componentDidMount. In this example, we init moesif-browser-js in the root /pages/_app.js.

Add your application id to /pages/_app.js

moesif.init({
  applicationId: "Your Moesif Application Id",
});

In the browser, assign moesif to the windows global space, so anywhere on the client side, you can reference window.moesif to track any user actions or trigger identifyUser (usually when user sign up or logs in).

Try it out by go to https://localhost:3000 in a browser.