Giter Site home page Giter Site logo

treblle / treblle-node Goto Github PK

View Code? Open in Web Editor NEW
36.0 8.0 3.0 55 KB

The official Treblle SDK for NodeJS/ExpressJS/NestJS. Seamlessly integrate Treblle to manage communication with your dashboard, send errors, and secure sensitive data.

Home Page: https://www.treblle.com/

License: MIT License

JavaScript 100.00%
nodejs api api-monitoring api-observability backend developer-tool express expressjs-api logging nodejs-expressjs

treblle-node's Introduction

Treblle for Node

Latest Version Total Downloads MIT Licence

Treblle makes it super easy to understand what’s going on with your APIs and the apps that use them. Just by adding Treblle to your API out of the box you get:

  • Real-time API monitoring and logging
  • Auto-generated API docs with OAS support
  • API analytics
  • Quality scoring
  • One-click testing
  • API managment on the go
  • and more...

Requirements

  • nodejs

Dependencies

Installation

You can install Treblle for Node via NPM. Simply run the following command:

$ npm install treblle

Don't forget to load the required JS modules in your app.js like so:

const express = require("express");
const { useTreblle } = require("treblle");

Getting started

Next, create a FREE account on https://treblle.com to get an API key and Project ID. After you have those simply initialize Treblle in your app.js file like so for Express:

const app = express();
app.use(express.json());

useTreblle(app, {
  apiKey: "_YOUR_API_KEY_",
  projectId: "_YOUR_PROJECT_ID_",
});

That's it. Your API requests and responses are now being sent to your Treblle project. Just by adding that line of code you get features like: auto-documentation, real-time request/response monitoring, error tracking and so much more.

Koa integration

If you're using koa, then you can enable Treblle like this:

const Koa = require("koa");
const KoaRouter = require("koa-router");
const KoaBody = require("koa-body");
const { koaTreblle } = require("treblle");

const app = new Koa();
const router = new KoaRouter();

app.use(
  koaTreblle({
    apiKey: "_YOUR_API_KEY_",
    projectId: "_YOUR_PROJECT_ID_",
  })
);

Strapi integration

Treblle has support for Strapi as well, to start using it you need to define the middleware first and then enable the middleware.

This guide is based on the strapi quickstart project, you can create it and follow by running the following command:

npx create-strapi-app my-project --quickstart

First define the middleware in middlewares/treblle/index.js like this:

const { strapiTreblle } = require("treblle");

module.exports = (strapi) => {
  return {
    initialize() {
      strapi.app.use(
        strapiTreblle({
          apiKey: "_YOUR_API_KEY_",
          projectId: "_YOUR_PROJECT_ID_",
        })
      );
    },
  };
};

Then enable the Treblle middleware in config/middleware.js like this:

module.exports = {
  settings: {
    treblle: {
      enabled: true,
    },
  },
};

Cloudflare Workers integration

Service workers

To use external packages (like Treblle) inside your workers you need a bundler (eg. Webpack or Rollup) to gather all dependencies into a single file which can be then deployed to Cloudflare. Read more about it in Cloudflare webpack & configuration official documentation, and in an official example.

Example - Wrangler's webpack

# wrangler.toml

...
type = "webpack"
webpack_config = "webpack.config.js"

[build.upload]
format = "service-worker"
// webpack.config.js

module.exports = {
  entry: "./index.js",
  target: "webworker",
  mode: "production",
  output: {
    filename: "worker.js",
  },
};
// worker.js

const { serviceWorkerTreblle } = require("treblle");

// Call this function for initialization, Treblle will attach itself to the 'fetch' event to be able to listen for response
const treblle = serviceWorkerTreblle({
  apiKey: "_YOUR_API_KEY_",
  projectId: "_YOUR_PROJECT_ID_",
  additionalFieldsToMask: ['key1', 'key2'], // Optional
  showErrors: true, // Optional, defaults to true
});

// Wrap your 'fetch' handler inside returned Treblle function, so Treblle can listen for unhandled application errors in your code
addEventListener(
  "fetch",
  treblle((event) => {
    event.respondWith(
      new Response("Hello worker!", {
        headers: { "content-type": "text/plain" },
      })
    );
  })
);

Module workers

Similar as with Service workers above, you need a bundler to package Treblle SDK together with your application code. Be sure to check out official Cloudflare documentation about webpack & modules configuration if you are stuck.

Here is also an official example of a setup with both Modules and CommonJS, using Webpack: link.

Example

// worker.js

import { moduleWorkerTreblle } from "treblle";

// Initialize Treblle with this function, and store Treblle wrapper inside a variable
const treblle = moduleWorkerTreblle({
  apiKey: "_YOUR_API_KEY_",
  projectId: "_YOUR_PROJECT_ID_",
  additionalFieldsToMask: ['key1', 'key2'], // Optional
  showErrors: true, // Optional, defaults to true
});

export default {
  // Wrap your 'fetch' handlers inside Treblle wrapper function to use it
  fetch: treblle(async (request) => {
    return new Response(JSON.stringify({ sample: "json" }), {
      headers: { "content-type": "application/json" },
    });
  }),
};

Important Note

Treblle package (currently) uses some Node native libraries for other integrations, like os & url, which are not supported in Cloudflare Workers Runtime. They are not used in this integration, so it is enough to polyfil them with empty modules.

// webpack.config.js

...
  resolve: {
    fallback: {
      os: false,
      url: false
    }
  }
...

NestJS (with Express)

// NestJS's boostrap function

const app = await NestFactory.create(AppModule);

...

const expressInstance = app.getHttpAdapter().getInstance();

useNestTreblle(expressInstance, {
  apiKey: "_YOUR_API_KEY_",
  projectId: "_YOUR_PROJECT_ID_",
});

...

Running Treblle only in production

If you want to run Treblle only in production, you can rely on the environment variables, or use a similar approach via config.

const app = express();
app.use(express.json());

if (process.env.NODE_ENV === "production") {
  useTreblle(app, {
    apiKey: "_YOUR_API_KEY_",
    projectId: "_YOUR_PROJECT_ID_",
  });
}

Need to hide additional fields?

If you want to expand the list of fields you want to hide, you can pass property names you want to hide by using the additionalFieldsToMask setting like in the example below.

useTreblle(app, {
  apiKey: "_YOUR_API_KEY_",
  projectId: "_YOUR_PROJECT_ID_",
  additionalFieldsToMask: ["secretField", "highlySensitiveField"],
});

Logging errors

For easier debugging when sending the data to Treblle errors are visible by default, you can control it via the showErrors flag, you can disable the errors with showErrors set to false:

useTreblle(app, {
  apiKey: "_YOUR_API_KEY_",
  projectId: "_YOUR_PROJECT_ID_",
  showErrors: false,
});

Support

If you have problems of any kind feel free to reach out via https://treblle.com or email [email protected] and we'll do our best to help you out.

License

Copyright 2021, Treblle Limited. Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

treblle-node's People

Contributors

akantic avatar cindreta avatar davorbadrov avatar henrychavez avatar kasrak2k avatar nikme avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

treblle-node's Issues

integration with next js api routes

Hey there, is there anyway of implementing useTreblle for nextjs api routes? It's quite coupled to be used with express but is there a way to make it in middleware's fashion of some sorts?

Thank you for the amazing library

"Sending data to Treblle failed"

i followed the dashboard's instructions to implement treblle in my api but on every call i get this error message in the console
[error] Sending data to Treblle failed - status: Forbidden (403) { message: 'Forbidden' }

Here is how i implemented treblle

const app = express();

app.use(json());

app.use(cors());
app.use(urlencoded({ extended: true }));

useTreblle(app, {
  apiKey: process.env.TREBLLE_API_KEY,
  projectId: process.env.TREBLLE_PROJECT_ID,
});

and here are my dependencies

  "dependencies": {
    "@types/node-cron": "^3.0.1",
    "axios": "^0.27.2",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "csv-parser": "^3.0.0",
    "date-fns": "^2.28.0",
    "express": "^4.17.1",
    "express-async-errors": "^3.1.1",
    "express-validator": "^6.13.0",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^6.0.14",
    "multer": "^1.4.3",
    "node-cron": "^3.0.0",
    "nodemailer": "^6.7.4",
    "treblle": "^1.2.0"
  }

my first thought was that i've setup my envs wrong but they seem to be correct, how can i fix it?

Hi Team, getting this issue while trying to integrate my node api with Treblle. Need help

This is a simple Typescript API but, Treblle is failing to handle the request.

[error] Sending data to Treblle failed (it's possibly a network error) TypeError: function () {
let value = container[varName]

  log(`will be read from the environment using "${accessor.name}" accessor`)

  if (typeof value === 'undefined') {
    if (typeof defValue === 'undefined' && isRequired) {
      log('was not found in the environment, but is required to be set')
      // Var is not set, nor is a default. Throw an error
      raiseError(undefined, 'is a required variable, but it was not set')
    } else if (typeof defValue !== 'undefined') {
      log(`was not found in the environment, parsing default value "${defValue}" instead`)
      value = defValue
    } else {
      log('was not found in the environment, but is not required. returning undefined')
      // return undefined since variable is not required and
      // there's no default value provided
      return undefined
    }
  }

  if (isRequired) {
    log('verifying variable value is not an empty string')
    // Need to verify that required variables aren't just whitespace
    if (value.trim().length === 0) {
      raiseError(undefined, 'is a required variable, but its value was empty')
    }
  }

  if (isBase64) {
    log('verifying variable is a valid base64 string')
    if (!value.match(base64Regex)) {
      raiseError(value, 'should be a valid base64 string if using convertFromBase64')
    }
    log('converting from base64 to utf8 string')
    value = Buffer.from(value, 'base64').toString()
  }

  const args = [value].concat(Array.prototype.slice.call(arguments))

  try {
    log(`passing value "${value}" to "${accessor.name}" accessor`)

    const result = accessor.apply(
      accessor,
      args
    )

    log(`parsed successfully, returning ${result}`)
    return result
  } catch (error) {
    raiseError(value, error.message)
  }
} is not a legal HTTP header value

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.