Astro 2.0 and TypeScript 5.0 beta

#​623 — January 27, 2023

Read on the Web

JavaScript Weekly

Astro 2.0: The Next-Gen ‘Islands’-Oriented Web Framework — 2.0 includes hybrid rendering (mixing of SSR and SSG outputs), type safety for Markdown & MDX, and an upgrade to Vite 4.0. Astro is worth exploring when performance is key as it works with popular frameworks but lets you deliver the least JS possible to get pages rendered.

Fred Schott

Prefer a talk? Nate Moore’s ViteConf talk ▶️ Islands Architecture, Astro, and You will bring you up to speed.

Deep Cloning Objects in JavaScript, The Modern Way — If you’ve been leaning on something like Lodash for deep cloning, you might not need to any longer. “It’s been a long time coming, but we finally now have the built-in structuredClone function to make deep cloning objects in JavaScript a breeze.”

Steve Sewell

Go From Professional Web Developer to Lead Engineer — Aspiring lead developer? Our collection of comprehensive video courses cover the fundamentals of JavaScript, TypeScript, React, web performance, and more.

Frontend Masters sponsor

Announcing TypeScript 5.0 Beta — A new major version number, but users of the popular typed JS superset will face a ‘similar upgrade experience’ to previously. Decorators make it in as a first class feature, significant performance and package size optimizations are present, export type * is supported, all enums are now union enums, and much more.

Daniel Rosenwasser (Microsoft)

AlaSQL.js 3.0: Isomorphic JavaScript SQL Database — A SQL database you can use in the browser, Node.js or mobile apps. An interesting bit of functionality is you can use SQL to query JavaScript objects – example. “The library adds the comfort of a full database engine to your JavaScript app. No, really.”

Andrey Gershun

IN BRIEF:

🏅 If you’re really into Vue.js, you’ll soon be able to become officially certified in it.

If you’re using React, you should be using a React framework, 🐦 says Andrew Clark of the core team.

The creator of alternative JS runtime Bun asks: “If there’s one thing missing from Bun for you to switch, what is it?” You can reply on Twitter.

jQAPI.com is an amazing meeting of old and new JavaScript – it’s an Astro powered version of jQuery’s documentation!

RELEASES:

Shoelace 2.0
↳ Agnostic library of web components.

μFuzzy 1.0
↳ Tiny fuzzy search library.

React Router 6.8

Node.js 19.5.0

📒 Articles & Tutorials

Getting Started with SvelteKit — SvelteKit only recently hit 1.0 and this is a comprehensive overview of how to build a site using the Svelte-oriented app framework. It covers topics like routing, layouts, data, props and more.

Adam Rackis

Using .NET Code from JavaScript using WebAssembly“Starting with .NET 7, you can easily run any .NET method from JavaScript without needing the whole Blazor framework.”

Gérald Barré

JavaScript Scratchpad for VS Code (2m+ Downloads) — Quokka.js is the #1 tool for exploring/testing JavaScript with edit-continue experience to see realtime execution and runtime values.

Wallaby.js sponsor

scrollend: A New JavaScript Event — Finally an event you won’t need a hotel booking for. scrollend provides a new way to detect that a scrolling operation is complete in the browser. Is it another Chrome-only nicety? Surprisingly not – Firefox 109+ supports it too.

Adam Argyle (Chrome Team)

Packaging Rust Apps for the npm Registry — Isn’t npm just for JavaScript projects? Nope. Node is required to make this technique work, but as long as you can package and execute a binary, you’re good to go.

Orhun Parmaksız

Making Sense of TypeScript using Set Theory — This article certainly doesn’t hang around. Neat diagrams too.

Vladimir Klepov

React Authentication, Simplified

Userfront sponsor

Accessible Hamburger Buttons without JavaScript — Sometimes you need to consider if modern techniques allow you to avoid JavaScript. Here’s a CodePen if you want to play.

Pausly

While we’re on the topic of less JavaScript, the latest episode of the Stack Overflow podcast ▶️ ‘The less JavaScript, the better’ focuses on Astro.

🛠 Code & Tools

Uppy 3.4: Powerful, Modular JavaScript File Uploader — Upload not just from local sources but even Dropbox or Instagram. Integrates with popular frameworks and supports resumable uploads. GitHub repo.

Transloadit

Nut.js 3.0: Desktop Automation from Node — Take control of your desktop (Windows, macOS or Linux) in code with control over keyboard + pointer, along with image matching functionality. GitHub repo.

Simon Hofmann

Optimize Your Systems’ Performance With TelemetryHub – Real-Time Data Monitoring & Analysis — An advanced data visualization and analysis tool that can help you identify and resolve unseen issues in your environment. Try free.

TelemetryHub by Scout sponsor

Eleventy v2.0: First Beta of the Popular Site GeneratorEleventy is a popular Node.js static site generator and v2.0 includes enough major changes that a thorough beta is needed. The creator ▶️ made this quick video about the release.

Zach Leatherman

Mock Service Worker 1.0: API Mocking Library for Browser and Node — Intercepts requests which you can then mock. Capture outgoing requests using an Express-like routing syntax, complete with parameters, wildcards, and regexes. GitHub repo.

Artem Zakharchenko

Drift: A Self-Hostable Gist-Like / Pastebin Service — Built with Next.js 13.

Max Leiter

Dygraphs 2.2
↳ Interactive charts of time series data.

actions/github-script 6.4
↳ Write GitHub Actions workflows in JS.

Playwright 1.30
↳ Browser automation framework.

Faast.js 6.4
↳ Serverlessly call JS functions on AWS Lambda & Google Cloud Functions.

Cypress 12.4
↳ Testing framework for anything in a browser.

D3plus 2.1
↳ Extend D3.js with more visualization types.

💻 Jobs

Developer Relations Manager — Join the CKEditor team to build community around an Open Source project used by millions of users around the world 🚀

CKEditor

Senior Full-Stack Engineer – React + TypeScript — Come help Qwire modernize how studios, composers, artists, publishers, labels, and the rest of the industry manage music rights.

Qwire

Find JavaScript Jobs with Hired — Create a profile on Hired to connect with hiring managers at growing startups and Fortune 500 companies. It’s free for job-seekers.

Hired

Nodesource introduces Machine learning on its N|Solid platform to help make better Node Apps

N|Solid is an incredibly versatile platform for helping developers and devops engineers build and manage highly performant and secure Node.js web applications. With the advancement of machine learning you can unlock even more potential. Our M/L solution is a powerful tool that can increase the quality of user experience and boost efficiency for organizations with their Node.js applications. In this article, we’ll explore what machine learning is and how you can use it within N|Solid, pluswe’ll provide tips and best practices for leveraging this new capability to get the most out of your Node.js project.

AI – growing in value in the software development lifecycle

Img #1 AI vs ML concepts

Put in context, artificial intelligence refers to the general ability of computers to emulate human thought and perform tasks in real-world environments, while machine learning refers to the technologies and algorithms that enable systems to identify patterns, make decisions, and improve themselves through experience. — https://ai.engineering.columbia.edu

The technology world has been abuzz with the growing hype of artificial intelligence (AI). This is understandable as AI promises to revolutionize business and everyday life; from self-driving cars to automated customer service, AI will shape the future of our civilization. As technology continues to advance, the potential applications for AI are seemingly endless.

AI and ML (Machine Learning) are closely related, but not identical. AI is the broader concept of machines being able to perform tasks that would normally require human intelligence, such as visual perception, speech recognition, decision-making, and language understanding. ML is a specific subset of AI that is focused on the development of algorithms and statistical models that allow computers to “learn” from data, without being explicitly programmed. In other words, ML is a method for achieving AI.

ML and AI can help developers build better software in several ways. Some examples include:

Automating repetitive tasks: ML algorithms can be used to automate repetitive tasks that would otherwise require human intervention. For example, a ML model could be trained to automatically classify and categorize emails, reducing the need for manual sorting.

Improving software performance: ML algorithms can be used to optimize the performance of software systems. For example, a ML model could be trained to predict the load on a server, allowing the software to dynamically adjust its resource usage in response.

Enhancing the user experience: AI-powered software can provide a more personalized and intuitive experience for users. For example, a chatbot powered by natural language processing (NLP) could be used to provide customer service, or a recommendation system powered by ML could be used to suggest products to customers.

Predictive Maintenance: AI and ML algorithms can be used to predict when a machine or equipment is likely to fail, allowing maintenance to be performed before the failure occurs.

Identify and Fix Bugs: AI and ML can be used to automatically identify and fix software bugs, reducing the need for human intervention.

Improve Cybersecurity: AI and ML can be used to identify and mitigate cyber threats and detect suspicious activity on a network, which help to improve cybersecurity.

We believe there is great promise for developers to leverage new tooling that helps them focus on the solution and resolve issues as fast as possible, reducing security risks and deliver amazing user experiences. We see AI and ML as a major step forward to build better software.

Node.js expose the potential of AI.

Img 2 – AI Frameworks

We believe Node.js is a powerful technology for leveraging the potential of AI. It allows developers to easily create and manage AI applications, as it features extensive APIs for interacting with AI-related services. With Node.js, developers can create AI-backed applications that can be deployed across various platforms, making it an invaluable asset for businesses looking to leverage the power of AI.

The combination of Node.js and AI will also make it possible to create sophisticated applications that can interpret data in real-time, allowing businesses to improve their customer experience dramatically. As AI advances, Node.js will be a key tool in helping developers make the most out of the technology.

Recently there are several AI projects that are ushering a massive wave of exploration. OpenAI and its ChatGPT has become one of the fastest tools ever adopted. We are impressed with the incredible progress of the OpenAI project and many others,we continue to study, experiment, and review implementations of these technologies and their potential for the ecosystem.

Links to other cool resources

GitHub OpenAI: https://github.com/openai/openai-quickstart-node

OpenAI Docs: https://beta.openai.com/docs/quickstart

Already, Node.js is being used by many companies to power their AI-driven applications, and this trend will only continue as more companies seek to take advantage of the power of AI. Node.js also allows developers to quickly set up and deploy AI-driven applications, further accelerating the development process. With Node.js and AI, businesses can create smarter, faster, and more efficient applications.

Nodesource Introduces Machine learning in N|Solid platform

N|Solid is a Node.js platform with an integrated AI development environment.

This feature allows for training models that will later detect similar patterns in your application data and fire custom events.

It also offers advanced analytics capabilities and support for various AI technologies, making it a powerful tool for businesses looking to capitalize on the potential of AI.

Img 3 – ML Feature Cover

N|Solid is part of a larger trend toward making AI and ML more accessible to developers, helping to utilize these advancements to deliver software solutions.. By providing an integrated platform for Node.js in production, N|Solid is making it easier for businesses to create sophisticated AI-driven models and reap the benefits that come with them.

Developers can start using this new feature in N|Solid immediately to:

Identify performance issues and present insights to resolve quickly
Apply insights across multiple applications
Smart analysis and detection of common Node.js performance issues with the bundled models we provide
Training of custom models to detect specific problems
Global notifications and events tracking for processes and applications

Below you will see ML in action inside N|Solid.

Machine Learning UI

In the N|Solid Console, the Machine Learning feature can be accessed from the app summary or process detail views.

Each handles different data sets and will have a different effect on the model you train.

Training ML Models

The Machine Learning models can be trained using two kinds of data sets. The models trained in the app summary view will use the aggregated data of all the processes running inside the app.

On the other hand, the models trained in the process detail view will use process-specific data.

Train a model in the app summary view.

When a process/app is first connected, it will take a certain amount of data to be successfully trained; you will find a progress loader under process configuration:

To train a model in an app summary page, click on Train ML Model button.

Train a model in a process detail view.

To train a model in a process detail page, click on Train ML Model button.

Modal creation and training

After clicking on the Train ML Model button, a modal will open; here, you can create, filter, and train models; this modal is the same for both pages.

To create a model, click on CREATE NEW MODEL.

Name and briefly describe the model, then save.

Select the created modal and click on ‘TRAIN.’

When the trained model finds a data pattern similar to the one it was trained with, it will fire an event and show a banner on top of the navbar.

Click on View Event to be redirected to the events tab; here, you will find the most recent machine learning event.

The events will also appear in the application status section; clicking on VIEW ANOMALIES will redirect to the events tab.

Manage the default and custom models.

Machine Learning models can be administered in the settings tab, where you will find a set of default models and the user-trained models; here, the frequency of events being fired can be modified, and the custom user models can be deactivated, deleted, or edited.

For a full reset of the created models, click on RESET MODELS.

Custom user models have edit and delete icons; these models are found beneath the default models.

PLEASE NOTE Only the name and description of the user-created model can be edited; if you want to change the model data, please retrain the model in-app summary or in the process detail pages. Default models are activated by default; these can only be activated or deactivated.

Our Machine learning feature has been live since November 2022; if you want to review the official documentation, you can do it here.

One Last Thing…

To get the best out of Enterprise Node.js, start a free trial of N|Solid SaaS, an augmented version of the Node.js runtime, enhanced to deliver low-impact performance insights and greater security for mission-critical Node.js applications.

Why document.write() is bad

#​622 — January 20, 2023

Read on the Web

JavaScript Weekly

Why Not document.write()? — Many moons ago, document.write was a mainstay of client-side JavaScript code, but it’s long been considered a bad practice – why? Harry digs in, noting that it “guarantees both a blocking fetch and a blocking execution, which holds up the parser for far longer than necessary”.

Harry Roberts

New: The WebAssembly JavaScript Promise Integration API — A technical explanation from the V8 team on a new API to let WebAssembly apps bridge the synchronous / asynchronous gap of expectations around external functionality (consider that many apps are written synchronously, but modern Web APIs are usually asynchronous). JSPI helps bridge both worlds and can be tested via a flag in Chrome.

McCabe, Michaud, Rezvov, Dahl / V8 Team

Break the Programming Mold with Dependency Injection — Keep your code on the cutting edge with dependency injection in JavaScript. Check out Snyk’s guide that gives a breakdown of what dependency injection is, when you should use it, and what popular JavaScript frameworks it’s implemented.

Snyk sponsor

Why Is My Jest Suite So Slow?Jest is known for its speed and simplicity so the author was surprised at how quickly his team’s test suite was slowing down. This is a write up of the ensuing investigation along with the improvements that slashed test running time.

Steven Lemon

Bun v0.5 ReleasedBun is another JavaScript runtime taking the world by storm and a level of Node compatibility has been baked in from the start. v0.5 adds support for node:readline, workspaces, a node:dns shim, and network socket creation support such that more Node.js-based database libraries work out of the box.

Ashcon Partovi

IN BRIEF:

The ▶️ latest episode of the JS Party podcast tackles ‘the rise and fall’ of JavaScript frameworks and the modern trend towards smaller ones.

The folks at NodeSource have put together a top 10 list of Node open-source projects ‘to keep an eye on’ in 2023.

Aurelia 2 is now in beta.

RELEASES:

⭐️ esbuild 0.17.0
↳ Popular bundler. Note that this is a key release with backwards incompatible changes.

Inertia.js 1.0
↳ Build SPAs for any backend.

React Native 0.71

Remix 1.10.0
↳ Popular full stack framework.

📒 Articles & Tutorials

🎨  Building an Accessible Theme Picker — An attractively presented, easy to follow tutorial for a handy site feature.

Sarah L. Fossheim

Fixing a Memory Leak in a Production Node.js App — Kent encountered a variety of weird memory and CPU usage spikes in his Node-powered app and decided to figure out what was going on. This post walks through his complete journey, with plenty of side problems encountered along the way, before discovering the root cause was where he least expected it.

Kent C Dodds

Build a Mobile-Responsive Telehealth Pager App Using Stream’s Chat API — Build a responsive chat app with emojis/reactions, built-in GIF support, ability to edit/delete messages, direct & group chat, and more.

Stream sponsor

📊  A Beginner’s Guide to Chrome Tracing — For when you want to go deeper than the Performance tab. With tracing, you can record what a browser is up to far behind the scenes.

Nolan Lawson

Handling Errors Like a Pro in TypeScript“Learn the design pattern I use to handle errors and write cleaner code.”

Kolby Sisk

A Beginner’s Guide to async/await with Examples

James Hibbard

10 Mistakes to Avoid When Starting with Vue 3

Fotis Adamakis

🛠 Code & Tools

RoughNotation: Cute Animated ‘Rough’ Text Annotations — Uses Rough.js (itself a project worth checking out) to get a hand-drawn look. Lots of nice interactive examples on the page showing a variety of annotation styles (boxes, underlines, circles..)

Preet Shihn

Free Website Speed Test: Does Your Site Meet Google’s Core Web Vitals? — Get an in-depth technical analysis of your site and learn how to make it fast. Rank higher in Google & deliver great UX.

DebugBear sponsor

Modern Errors: Handle Errors in a Simple, Stable, Consistent Way — Create error classes, wrap or aggregate errors, or use one of several plugins to do things like print bug reporting info, print stack traces, or more. Happy in both Node and the browser.

ehmicky

Shifty: A Small, Fast Tweening EngineAll it does is tweening. It’s a low level animation solution that you can integrate into any rendering mechanism of your choice. The examples here demonstrate it well as it can be used for ‘animating’ things in an unconventional sense. GitHub repo.

Jeremy Kahn

Barba.js: For Smooth Visual Transitions Between Pages — You certainly can’t say the project’s homepage doesn’t show off all of its features! For such a dramatic set of effects, things feel smooth and.. surprisingly tolerable 😁 GitHub repo.

De Rosa, Michel, et al.

Rete.js 1.5: A Framework for Visual Programming — Create a node-based editor in the browser and apply logic. Check out these demos on CodePen. GitHub repo.

Vitaliy Stoliarov

Don’t Let Your Issue Tracker Be a Four-Letter Word. Use Shortcut

Shortcut (formerly Clubhouse.io) sponsor

gpu-io: GPU-Accelerated Computing Library — for physics simulations and other mathematical calculations. A neat look at the power of WebGL. Several examples.

Amanda Ghassaei

Chart.js 4.2
↳ Simple Canvas-based charts. (Samples.)

Serialize JavaScript 6.0.1
↳ Serialize JS to a JSON superset.

axios-retry 3.4
↳ Axios plugin that retries failed requests.

Axios 1.2.3 – Popular HTTP client library.

Commander.js 10.0 – Node.js CLIs made easy.

Mineflayer 4.7 – JS API for Minecraft bots.

Wretch 2.4 – Fetch API wrapper with niceties.

💻 Jobs

Developer Relations Manager — Join the CKEditor team to build community around an Open Source project used by millions of users around the world 🚀

CKEditor

Find JavaScript Jobs with Hired — Create a profile on Hired to connect with hiring managers at growing startups and Fortune 500 companies. It’s free for job-seekers.

Hired

Interview With Italo José Core committer at @herbsjs

@ItaloJosé is Microsoft MVP in the Node.js category and works at NodeSource as a Software Engineer; He organizes CityJS Brazil.

We are thrilled to be part of developing powerful tools like N|Solid. We are immensely proud of our engineers who have dedicated their time and expertise to support the open-source ecosystem. This is our way of giving voice and visibility to the projects they are passionate about.

We want to recognize Italo José’s work with Herb.js on this occasion. He has been working on the Herbs.js project since 2020, where he developed the initial versions of the CLI, made significant contributions to numerous repositories, and mentored new contributors.

NS: What benefits does Herbs.js provide?

IJ: Different from other frameworks that help you to write a better infrastructure layer, like the API, database layer, documentation, and tests. The Herbs.js want to help you avoid writing it and focus on what matters, the domain’s code. How do we do it? We read your use case and provide you with the infrastructure; this way, you can save more than 50% of the time developing a server-side application.

It’s good for the business and developers that will stop writing boring and repetitive code for every project.

NS: How can I use Herbs.js to improve my development process?

IJ: The first step is writing your entities and use cases using the @herbsjs/herbs library, besides you have a more organized and readable use cases’ code. After that, you can add our glues(other libraries) that will read your use case and provide you the infrastructure code like rest or GraphQL APIs, documentation, repositories layer and more.

NS: What are the most popular features of Herbs.js?

IJ: Our CLI, the herbs2rest libraries.
The CLI, you know, helps you to generate and maintain a project using the Herbs.js. The herbs shelf reads your use cases and provides human documentation (this is my favorite).

The herbs2rest plugin reads your use case and provides a configured express instance containing all endpoints, an error handling layer, and auth layer for you.

These are the three most popular, but we have plugins for GraphQL, databases, tests, and more.

NS: How does Herbs.js simplify the development process?

IJ: Besidesprevents you writing 80% of the infrastructure code; we provide you with and structured way to write the use cases that allow you to maintain your code self-documented and organized in steps; it’s interesting because this way, new developers and non-developers can understand in a fast way what is happening in your code, it allows for example, project owners validate your use case rule for going to production.

Besides, we save time by avoiding writing the “repetitive” infrastructure code in all projects in our lives.

NS: How user-friendly is Herbs.js?

IJ: It’s pretty simple; as I mentioned in question 2, you write your entities and use case using the @herbsjs/herbs, and after that, just pass it for the glues, so the magic happens.

We assume you want to know more about this project. In that case, we invite you to review this amazing keynote that Italo left for the Community at CityJS Conference: Do you really code domain-oriented systems?

Want to contribute to an OS Project?

At NodeSource we released a project to compare the main APMs and thus help developers make decisions with real data. Here you can view the project and contribute directly to our GitHub repository.

If you have any questions, please contact us at [email protected] or on Twitter @nodesource. To get the best out of Node.js, try N|Solid SaaS #KnowYourNode

Instrument your Nodejs Applications with Open Source Tools – Part 2

As we mentioned in the previous article, at NodeSource, we are dedicated to observability in our day-to-day, and we know that a great way to extend our reach and interoperability is to include the Opentelemetry framework as a standard in our development flows; because in the end our vision is to achieve high-performance software, and it is what we want to accompany the journey of developers in their Node.js base applications.

With this, we know that understanding the bases was very important to know the standard and its scope, but that it is necessary to put it into practice. How to integrate Opentelemetry in our application?; and although NodeSource has direct integration into its product in addition to more than 10 key functionalities in N|Solid, that extend the offer of a traditional APM, as you know, we are great contributors to the Open Source project, we also support the binary distributions of the Node.js project, our DNA is always helping the community and showing you how through Open Source tools you can still increase the visibility. So through this article, we want to share how to set up OpenTelemetry with Open Source tools.

In this article, you will find __How to Apply the OpenTelemetry OS framework in your Node.js Application__, which includes:

Step 1: Export data to the backend

Step 2: Set up the Open Telemetry SDK
__Step 3__: Inspect Prometheus to review we’re receiving data

Step 4: Inspect Jaeger to review we’re receiving data

Step 5: Getting deeper at Jaeger 👀

Note: This article is an extension of our talk at NodeConf.EU, where we had the opportunity to share the talk:

__Dot, line, Plane Trace!__
__Instrument your Node.js applications with Open Source Software__
Get insights into the current state of your running applications/services through OpenTelemetry. It has never been as easy as now to collect data with Open Source SDKs and tools that will help you extract metrics, generate logs and traces and export this data in a standardized format to be analyzed using the best practices. In this talk, We’ll show how easy it is to integrate OpenTelemetry in your Node.js applications and how to get the most out of it using Open Source tools.

To see the talks from this incredible conference, you can watch all sessions through live-stream links below 👇
– Day 1️⃣ – https://youtu.be/1WvHT7FgrAo
– Day 2️⃣ – https://youtu.be/R2RMGQhWyCk
– Day 3️⃣ – https://youtu.be/enklsLqkVdk

Now we are ready to start 💪 📖 👇

Apply the OpenTelemetry OS framework in your Node.js Application

So, going back to the distributed example we described in our previous article, here we can see what the architecture looks like this after adding observability.

Every service will collect signals by using the OpenTelemetry Node.js SDK and export the data to specific backends so we can analyze it.

We are going to use the following:

JAEGER for Traces and Logs.

Prometheus to visualize the metrics.

_Note: _Jaeger and Prometheus are probably the most popular open-source tools in space.

Step 1: Export data to the backend

How the data is exported to the backends differs:
To send data to _JAEGER__, we will use OTLP over HTTP, whereas for _Prometheus__, the data will be pulled from the services using HTTP.

First, we will show you how easy it is to set up the OpenTelemetry SDK to add observability to our applications.

### Step 2: Set up the OpenTelemetry SDK

First, we have the providers in charge of collecting the signals, in our case __NodeTracerProvider__ for traces and __MeterProvider__ for metrics.
Then the exporters send the collected data to the specific backends.
The Resource contains attributes describing the current process, in our case, __ServiceName__ and __Container. Id’s__. The name of these attributes is well defined by the spec (it’s in the __semantic_conventions module__) and will allow us to differentiate where a specific signal comes from.

So to set up traces and metrics, the process is basically the same: we create the provider passing the Resource, then register the specific exporter.

We also register instrumentations of specific modules (either core modules or popular userspace modules), which provide automatic Span creation of those modules.

Finally, the only important thing to remember is that we need to initialize OpenTelemetry before our actual code; the reason is these instrumentation modules (in our case for __http__ and fastify) __monkeypatch__ the module they’re instrumenting.

Also, we create the __meter instruments__ because we will use them on every service: an __HTTP request counter__ and a couple of observable gauges for __CPU usage__ and __ELU usage__.

So let’s spin the application now and send a request to the API. It returns a 401 Not Authorized. Before trying to figure out what’s going on, let’s see if Prometheus and jaeger are actually receiving data.

Step 3: Inspect Prometheus to review we’re receiving data

Let’s look at Prometheus first:
Looking at the HTTP requests counter, we can see there are 2 data points: one for the __API service__ and another one for the __AUTH service__. Notice that the data we had in the Resource is __service_name__ and __container_id__. We also can see the process_cpu is collecting data for the 4 services. The same is true for __thread_elu__.

Step 4: Inspect Jaeger to review we’re receiving data

Let’s look at Jaeger now:
We can see that one trace corresponding to the __HTTP request__ has been generated.

Also, look at this chart where the points represent traces, the X-axis is the timestamp, and the Y-axis is the duration. If we inspect the trace, we can see it consists of 3 spans, where every span represents an __HTTP transaction__, and it has been automatically generated by the instrumentation-HTTP modules:

The 1st span is an HTTP server transaction in the API service (the incoming HTTP request).
The 2nd span represents a POST request to AUTH from API.
The 3rd one represents the incoming HTTP POST in AUTH. If we inspect a bit this last span, apart from the typical attributes associated with the request (HTTP method, request_url, status_code…).

We can see there’s a Log associated with the Span this makes it very useful as we can know exactly which request caused the error. By inspecting it, we found out that the reason for the failure was missing the auth token.

This piece of information wasn’t generated automatically, though, but it’s very easy to do. So in the verify route from the service, in case there’s an error verifying the token, we retrieve the active span from the current context and just call __recordException()__ with the error. As simple as that.

Well, so far, so good. Knowing what the problem is, let’s add the auth token and check if everything works:

curl http://localhost:9000/ -H “Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIiLCJpYXQiOjE2NjIxMTQyMjAsImV4cCI6MTY5MzY1MDIyMCwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoiIiwibGljZW5zZUtleSI6ImZmZmZmLWZmZmZmLWZmZmZmLWZmZmZmLWZmZmZmIiwiZW1haWwiOiJqcm9ja2V0QGV4YW1wbGUuY29tIn0.PYQoR-62ba9R6HCxxumajVWZYyvUWNnFSUEoJBj5t9I”

Ok, now it succeeded. Let’s look at Jaeger now. We can see the new trace here, and we can see that it contains 7 spans, and no error was generated.

Now, it’s time to show one very nice feature of Jaeger. We can compare both traces, and we can see in grey the Spans that are equal, whereas we can see in Green the Spans that are new. So just by looking at this overview, we can see that if we’re correctly Authorized, the API sends a GET request to SERVICE1, which then performs a couple of operations against POSTGRES. If we inspect one of the POSTGRES spans (the query), we can see useful information there, such as the actual QUERY. This is possible because we have registered the instrumentation-pg module in SERVICE1.

And finally, let’s do a more interesting experiment. We will inject load to the application for 20 seconds with autocannon…

If we look at the latency chart, we see some interesting data: up until at least the 90th percentile, the latency is basically below 300ms, whereas starting at least from 97.5%, the latency goes up a lot. More than 3secs. This is Unacceptable 🧐. Let’s see if we can figure out what’s going on 💪.

Step 5: Getting deeper at Jaeger 👀

Looking at Jaeger and limiting this to like 500 spans, we can see that the graph here depicts what the latency char showed. Most of the requests are fast, whereas there are some significant outliers.

Let’s compare one of the fast vs. slow traces. In addition to querying the database, we can see the slow trace in that SERVICE1 sends a request to SERVICE2. That’s useful info for sure. Let’s take a look more closely at the slow trace.

In the __Trace Graph view__, every node represents a Span, and on the left-hand side, we can see the percentage of time with respect to the total trace duration that the subgraph that has this node as root takes. So by inspecting this, we can see that the branch representing the HTTP GET from SERVICE1 to SERVICE2 takes most of the time of the span. So it seems the main suspect is SERVICE2. Let’s take a look at the Metrics now. They might give us more information. If we look at the thread.elu, we can see that for SERVICE2, it went 100% for some seconds. This would explain the observed behavior.

So now, going to the SERVICE2 code route, we can easily spot the issue. We were performing a __Fibonacci operation__. Of course, this was easy to spot as this is a demo, but in real scenarios, this would not be so simple, and we would need some other methods, such as CPU Profiling, but regardless, the info we collected would help us narrow down the issue quite significantly.

So, that’s it for the demo. We’ve created a repo where you can access the full code, so go play with it! 😎

Main Takeaways

Finally, we just want to share the main takeaways about implementing observability with Open Software Tools:

Setting up observability in our Node.js apps is actually not that hard.
It allows us to observe requests as they propagate through a distributed system, giving us a clear picture of what might be happening.
It helps identify points of failure and causes of poor performance. (for some cases, some other tools might also be needed: CPU profiling, heap snapshots).
Adding observability to our code, especially tracing, comes with a cost. So Be cautious! ☠️But we are not going to go deeper into this, as it could be a topic for another article.

Before you go

If you’re looking to implement observability in your project professionally, you might want to check out N|Solid, and our ’10 key functionalities’. We invited you to follow us on Twitter and keep the conversation!

Looking at both 2022 and 2023

#​620 — January 6, 2023

Read on the Web

We’re back for 2023 😀 As is our tradition, we’re taking a quick look back at the past year – this time led by a few choice retrospectives, then followed by the most popular articles and tools included in JavaScript Weekly in 2022. There’s sure to be some things you missed or want to revisit – enjoy!
__
Peter Cooper and the Cooperpress team

JavaScript Weekly

🌟 The 2022 JavaScript Rising Stars — For the seventh time, Michael Rambeau kicks off our year with a roundup of ‘trending projects’ in the JavaScript space. Bun takes the top spot for 2022, but we’ll leave the rest for you to check out. A few guest authors also share their opinions on the ecosystem.

Michael Rambeau et al.

Evan You Looks at 2022 and 2023 — You’ll know Evan for Vue.js and Vite and here he recaps what happened in the Vue world in 2022 (like Vue 3.x becoming the new default version) and what we can expect in 2023, including the mysteriously named Vapor Mode.. We’re also warned Vue 2.x has one year before it reaches EOL.

Evan You

🧈 Retire your Legacy CMS with ButterCMS — ButterCMS is your new content backend. We’re SaaS so we host, maintain, and scale the CMS. Enable your marketing team to update website + app content without needing you. Try the #1 rated SaaS Headless CMS for your JS app today. Free for 30 days.

🧈 ButterCMS sponsor

Six JavaScript Projects to Watch in 2023 — A reasonable selection, focused on newer, more cutting edge, but also very promising projects (including the aforementioned Bun).

AsyncBanana

LOOKING BACK AND FORWARD:

Michael Shilman writes about the future for Storybook in 2023.

Ryan Carniato ponders where JS frameworks are headed in 2023.

📅 ▶️ 10 JavaScript conferences to consider attending this year.

Some other 2022 roundups and reflections: Cassidy Williams, Igalia Web Platform Team, Dave Rupert, Stéphanie Walter, Pawel Grzybek, Stephanie Eckles, Michelle Barker, Rachel Andrew, Remy Sharp, Ahmad Shadeed, the HTTP protocol 😆

RELEASES:

Spacetime 7.4 – Lightweight timezone library.

Lerna 6.4 – JS monorepo build tool.

TestCafe 2.2 – End-to-end Web testing.

Vuetify 3.1 – Vue component framework.

📒 Top Articles & Tutorials of 2022

As determined by their popularity in JavaScript Weekly.

1. Douglas Crockford: “The best thing we can do today to JavaScript is to retire it.” — The most popular link of the year was to an interview with the author of JavaScript: The Good Parts (and discoverer-of-sorts of JSON) where he explained the benefits of code reading, why we need better languages, and how he won’t “write about JavaScript again.”

Evrone

2. Ecma International Approved ECMAScript 2022 — The second most popular item of the year was a bit more positive, with Ecma making ECMAScript 2022 a standard. Dr. Axel brought us up to speed with what this meant at a practical level. You’ll already be using some of these features – this move just tied up the formalities.

Dr. Axel Rauschmayer

▶  Whiskey Web and Whatnot: Your New Favorite JavaScript Podcast — A fireside chat with your favorite devs. Guests include Wes Bos, Charlie Gerard, Chris Coyier, and Kelly Vaughn.

Whiskey Web and Whatnot sponsorpodcast

3. JS Function Composition: What’s The Big Deal? — James’ articles on JavaScript fundamentals are always popular and last year we got a fresh one focusing on a common activity: function composition. “What’s the big deal?” he asks.

James Sinclair

4. AbortController is Your FriendAbortController provides a way to abort web requests at any point without waiting for a response but it’s possible to twist it into other use cases, as we saw here.

Sam Thorogood

5. Ten Common JavaScript Issues Developers Face — A good old-fashioned list. If you’ve been working with JavaScript for many years, these are potholes you (probably) know to avoid but there’s enough to chew on here otherwise.

Ryan J. Peterson

6. A Pipe Operator for JS: Introduction and Use Cases — Many developers feel a pipe operator is missing from JavaScript. Luckily there’s a pipeline operator proposal at stage 2 in TC39. Dr. Axel explains why you’d want this and how it could work.

Dr. Axel Rauschmayer

7. Patterns.dev: Modern Web App Design Patterns — A free book you can download in PDF format or enjoy on the Web. Learn about lots of fundamentals, from how different styles of rendering or importing resources work to performance optimizations and case studies.

Lydia Hallie, Addy Osmani, and Others

8. Decorators for ES6 Proposal Reached Stage 3 at TC39 — It’s a few years in the making, but a decorators proposal conditionally made it to stage 3 and people were very excited. Fingers crossed we see more from this in 2023.

Ecma TC39

🛠 Top Code & Tools of 2022

As determined by their popularity in JavaScript Weekly.

1. Rome Formatter: Super Fast JavaScript Formatting — I liked the image for this enough to want to include it again 😉 As of 2023, Rome (now at version 11) remains an ambitious project that sets out to replace a lot of JS tools in one hit with the initial focus being on Prettier-esque code formatting, as well as linting. Compiling, bundling, and testing features are scheduled to appear throughout 2023.

Rome Team

2. TypeScript 4.6 Released — Not a lot to say here, as TypeScript is always popular, and it’s now up to version 4.9, but with v4.6 it took a step forward by being able to detect more syntax errors in plain old JavaScript, a benefit for all JavaScript-developing VS Code users, at least.

Daniel Rosenwasser

Dynaboard: The Pro-Code Web App Builder Made for Developers — Build high performance public and private web apps in a collaborative — code forward — WYSIWYG environment.

Dynaboard sponsor

3. Vite 4.0 Released — This was only a month ago, too. From the same creator as Vue.js, Vite is an exciting piece of frontend tooling offering lots of goodies out of the box. We look forward to more Vite news in 2023.

Evan You and Vite Contributors

4. Lexical: An Extensible Text Editor Library — Out of Meta came a new text editor framework putting accessibility, performance, and reliability at its heart. At only 22KB gzipped and with React 18+ support (but vanilla is also OK), it reminded us of Draft.js but they say it’s the “next generation” and Meta is already replacing Draft.js with Lexical in their internal apps.

Meta / Facebook

5. Bun: A (Still) Interesting New JavaScript Runtime — Bun appeared in summer 2022 as a new JavaScript runtime built not around V8 (like Node.js or Deno are) but WebKit/Apple’s JavaScriptCore. It includes its own bundler, transpiler, task runner, and npm client, but most significantly boasts huge performance improvements over existing options and supported a lot of Node and Web APIs out of the box.

Jarred Sumner

6. JSON Crack: Visualize JSON Data in Graph Form — Got JSON, want to view it? This is a neat tool for working with and displaying JSON data structures. You can play with it online, embed the graphs into your site, or download them for further use.

Aykut Saraç

Stuck on Node 10? Need to Upgrade but Don’t Have Time? Contact Us 🚀

UpgradeJS.com | Node and JavaScript Upgrade Services sponsor

7. Shader Park: Create Interactive 2D and 3D Shaders with JavaScript — An open source Web-based platform, community, and library for simplifying the mystifying world of shaders and GPUs by letting you create them procedurally with JavaScript. Note: This site is heavy on the browser given its use of WebGL, so may not be suitable for every device.

Blankensmith and Whidden

8. Axios 1.0: The Popular HTTP Client Library/API — With 98k GitHub stars and a presence in numerous thousands of package.json files, Axios remains very popular and it’s amazing it only hit 1.0 in 2022. The Fetch API has taken much of Axios’ thunder but, like jQuery, Axios still wraps up a lot of functionality into a broadly liked API. (Official homepage.)

Axios Project

💻 Jobs

Developer Relations Manager — Join the CKEditor team to build community around an Open Source project used by millions of users around the world 🚀

CKEditor

Backend Engineer, TypeScript (Berlin / Remote) — Thousands of people love our product (see Trustpilot for yourself). Join the team behind it and help us scale. 🚀

Feather

Find JavaScript Jobs with Hired — Create a profile on Hired to connect with hiring managers at growing startups and Fortune 500 companies. It’s free for job-seekers.

Hired

We’re back to normal service as of next week! If you’ve got anything you’d like to submit for our consideration, hit reply and let us know.