Understanding Undici: A Node.js HTTP Client

Introduction to Undici

The Undici project is an HTTP/1.1 client written specifically for Node.js, aiming to provide a high-performance interface for making HTTP requests. Named after the Italian word for eleven ('Undici'), reflecting the HTTP/1.1 version that it supports, this client offers an alternative to the built-in http module in Node.js.

Features and Benefits

Undici boasts several features that make it an attractive choice for developers needing to perform HTTP requests in their Node.js applications:

  • Performance: Undici demonstrates superior performance compared to other HTTP clients available in Node.js, as evidenced by its benchmark results which showcase its ability to handle more requests per second.

  • Fetch API Compliance: Adhering to the Fetch Standard, Undici includes methods like fetch(), which developers familiar with the Fetch API in the browser will recognize and be able to use seamlessly in a Node.js environment.

  • Streaming and Pipelining: The client supports HTTP pipelining, allowing multiple requests to be sent out without waiting for the corresponding responses, as well as the ability to work efficiently with streams.

  • Garbage Collection Considerations: Given Node.js's less aggressive garbage collection compared to browsers, Undici recommends manually consuming response bodies to avoid issues such as excessive connection usage or deadlocks.

Installation and Usage

Installing Undici is straightforward, and it can be done using package managers like npm. Once installed, importing and using it is relatively simple, with methods available to send HTTP requests (undici.request), stream responses (undici.stream), and work with upgraded HTTP protocols (undici.upgrade). Here's a basic example of how to perform a GET request and print the response:

import { request } from 'undici';

const { statusCode, headers, body, trailers } = await request('http://localhost:3000/foo');
console.log('response received', statusCode);
console.log('headers', headers);
for await (const data of body) {
  console.log('data', data);
}
console.log('trailers', trailers);

Advanced Features

Apart from its basic usage, Undici provides several advanced features:

  • Body Mixins: Simplify the process of consuming response bodies by providing methods like .json(), .text(), and .formData().

  • Global Dispatcher: Configure a global dispatcher to manage how requests are made across an application.

  • Specification Compliance: While aiming to comply with HTTP/1.1 specifications, Undici also documents any deviations or unsupported features, such as the 'Expect' header.

  • Workarounds: For example, network address family autoselection can be controlled using the autoSelectFamily option in undici.request or the undici.Agent class.

Collaborators and Licensing

Undici benefits from the contributions of a community of collaborators, including notable individuals such as Matteo Collina and Robert Nagy, among others. The project is available under the MIT license, allowing for permissive free usage and contribution.

Conclusion

In summary, Node.js developers in search of a high-performance HTTP client that complies with the Fetch Standard may find Undici to be an excellent fit. Its fast performance, support for streaming and pipelining, and feature set aimed at both ease of use and compliance with standards make it a competitive choice in the landscape of Node.js HTTP clients.


Tags: #Undici #Nodejs #HTTPClient #FetchAPI #Performance

https://github.com/nodejs/undici

Analysis of the Proposed Zero-Runtime CSS-in-JS solution for Material UI and Joy UI

Overview

The proposal presents a new CSS-in-JS solution focused on minimal runtime overhead and compatibility with emerging React Server Components. It seeks to replace Emotion with a system that is robust and performs well on the server side.

Key Aspects of the RFC

Problem Statement

The proposal identifies the compatibility issue with React Server Components when using Emotion, a popular CSS-in-JS library, especially for structural components like Box and Typography. Since RSCs don't support states or contexts, current theming practices that rely on React Context are incompatible.

Requirements

The new CSS-in-JS solution must have minimal runtime to enhance performance and a small JS bundle size. It must also work with RSCs without dependency on unsupported APIs, support theme variables, and facilitate easy migration with minimal breaking changes. Additionally, the new solution should allow developers to easily navigate from the browser DevTools to the corresponding style definitions in the source code.

Options Considered

The proposal reviews several zero-runtime solutions including vanilla-extract, Linaria, PandaCSS, UnoCSS, and Stitches, identifying the strengths and limitations of each in the context of the requirements. For instance, vanilla-extract does not support theming out of the box, and Linaria requires separate tooling for theming and global styles.

Proposed Solution

The proposed solution involves adopting a compiled CSS-in-JS solution like linaria or compiled that supports the styled syntax and the sx prop. The proposed API includes support for theming, a styled utility from @mui/material, and the use of createTheme for defining component default properties and styling overrides. The API is designed to be intuitive, aligning with existing usage patterns within the Material UI ecosystem.

Example API Usage

The API allows for defining styled components with support for theming, variants, and default variants. It also enables conditional styling based on props and is designed to declaratively handle CSS generation and class name assignment.

Alternative Implementations

The proposal outlines alternative implementations that provide tailored solutions for different build tools, such as Vite and Next.js, through specific plugins, ensuring compatibility and optimized configurations for each environment.

Known Downsides

Some downsides of the first proposal are mentioned, including the need for additional configuration in next.config.js or vite.config.ts, as opposed to a simple install-and-use approach.

Resources and Benchmarks

The proposal provides references to playground apps created with Next.js and Vite to demonstrate the solution's feasibility and performance. It also refers to related GitHub issues that further discuss the implementation details and community feedback.

Conclusion

This RFC showcases a thoughtful approach to selecting a CSS-in-JS solution that will meet the future needs of Material UI and Joy UI, emphasizing performance, compatibility, and minimal disruption. The extensive review of available solutions and the detailed proposed API highlight a commitment to improving the development experience while adapting to the evolving React landscape.


Tags:

  • #CSSinJS
  • #ReactServerComponents
  • #MaterialUI
  • #Performance

https://github.com/mui/material-ui/issues/38137

WebAssembly Trends in 2023: Usage, Performance, Challenges & Future Outlook

The State of WebAssembly 2023

In the ever-evolving world of software development, one technology that has been progressively gaining momentum is WebAssembly (WASM). Its introduction has made waves, offering the performance of native computing with the safety guarantees of JavaScript. This article takes a dive into the state of WebAssembly in 2023, investigating modern usage, the performance benefits, and the challenges faced by developers

An Overview

WebAssembly is a binary instruction format, designed as a stack-based virtual machine. It can be a compilation target for languages like C, C++, Rust, and potentially more—plugging a gap in the web platform that was problematic for developers.

The Impetus: Why Developers Choose WebAssembly

Our study indicates that there are a cluster of compelling reasons that drive developers towards using WebAssembly. One significant factor is regarding performance – the consistent, predictable execution of a WebAssembly module provides massive performance boosts to web applications. Further, the inter-operation features provided by WebAssembly allow developers to use languages they are comfortable with, and target WebAssembly as the compilation target, thus widening adaptability.

The Difficulties: Challenges with WASM Adoption

While the positives are certainly worth noting, our investigation would not be complete without addressing the difficulties developers face when using WebAssembly. Taken from survey data, some of these challenges include insufficient multiprocessing support, the need for better debugging and profiling tools, and a lack in garbage collection capabilities. Addressing these challenges could improve developer experience and further the adoption of WebAssembly in projects.

Zooming In: WebAssembly System Interface (WASI)

Our report then dives into a particularized part of the WebAssembly landscape – the WebAssembly System Interface (WASI). WASI is an API and a capability-oriented security model that provides a system interface for WebAssembly applications. By understanding the levels of familiarity and key motivations behind WASI usage, we can shed light on areas for improvement and broader accessibility.

The Foresight: Future of WebAssembly

Developers remain optimistic about the future of this technology despite some current challenges. There’s an ongoing belief in the community that with some enhancements, WebAssembly could revolutionize software development in many sectors, enhancing web performance and usability.

In essence, the landscape of WebAssembly in 2023 is a blend of enthusiasm backed by measurable benefits, coupled with challenges that serve as signposts for future developments. As we move forward, it will be fascinating to see how the technology evolves and how its adoption influences the broader software development landscape.

[#Complete]

Tags: #WebAssembly #WASI #SoftwareDevelopment #Performance

Reference Link

Boosting Performance and Speed of Your Next.js Applications: Best Practices and Optimizations

The performance of an application is intimately linked with the time it takes to serve the application’s code, style elements, and data to the client during the first interaction. The application’s performance can degrade if the server needs to send additional assets like images during the initial interaction. Good news is, developers can employ several strategies to enhance the speed of their Next.js applications.

Leveraging Server-side Rendering

Server-side rendering (SSR) is a technique that involves rendering the initial HTML of a webpage on the server before delivering it to the web browser. Using SSR can decrease the time needed to render the first page on the client side, which means users get to see your page’s content much faster. In addition, SSR is beneficial for improving application performance, particularly on mobile devices.

Here’s an example of how you can use server-side rendering in your code:

// This function will be called by the server
export async function getServerSideProps({context}){
    // Fetch data from external API
    const res = await fetch(`YOUR_API`)
    // Returning the fetched data
    return {
        props: {
            data: res
        }
    }
}

The Power of Dynamic Imports

Traditionally, applications usually load all the necessary components and CSS during the initial load. Dynamic import, however, allows you to break your code into smaller chunks and load them on demand. This approach implies you can import particular components as and when they’re needed. For instance, you can lazy load the login component for users who aren’t logged in. To use dynamic imports, you should import your code via an ES2020 dynamic import.

Caching Frequently Used Content

For API routes, apply Cache-Control to enforce caching rules, like this:

export default function handler(req, res){
    res.setHeader('Cache-Control', 's-maxage=10')
}

And for server-side rendering:

export async function getServerSideProps({ req, res }){
    res.setHeader('Cache-Control','public, s-maxage=10, stale-while-revalidate=59')
    return { props: {} }
}

Next.js automatically adds caching for static files and assets, so you don’t need to manually set it.

Removing Unused Dependencies

Unused dependencies can increase the size and loading time of your app and may also cause unexpected behaviors. So, it’s always a good idea to keep track of the dependencies that aren’t in use and remove them.

Image Optimization

Image optimization, which includes reducing the size of image files and saving them in the correct format, can greatly improve performance. You can use the Next.js Image Component for this purpose.

Here’s an example:

import Image from 'next/image'

function OptimizedImage(){
    return (
        <>
            <h1>Optimized Image</h1>
            <Image 
                src={image_url} 
                alt="Any Text" 
                width={500} 
                height={500} 
                blurDataURL="URL" 
                placeholder="blur" 
            />
        </>
    )
}

export default OptimizedImage

Optimizing Your Scripts

Use Next.js script component to optimize your scripts. For instance:

import Script from 'next/script'

export default function OptimizedScript(){
    return (
        <>
            <Script 
                id="YOUR_ID" 
                src="URL" 
                onError={(err) => console.log('Error')} 
                onLoad={() => {
                    // Function to perform after loading the script
                }}
                strategy = "beforeInteractive"
            />
        </>
    )
}

Next.js is popular because it allows developers to build vibrant JavaScript apps without constructing backend infrastructure. Additionally, it is packed with features that can significantly improve application performance while carrying out most of the heavy lifting on the server. Following these best practices can help you harness these features and build faster Next.js applications.

Tags: #nextjs #performance #serversiderendering #dynamicimport
Reference Link

Building Faster, More Personalized Web with Vercel’s Frontend Cloud

Introduction

In today’s fast-paced digital world, speed and personalization are key factors in delivering a successful web experience. Developers need the proper tools and infrastructure to build websites that are not only fast but also tailored to the needs of their users. This is where Vercel’s frontend cloud comes in.

Vercel provides developers with the frameworks, workflows, and infrastructure to build a faster, more personalized web. With its native Next.js platform and cutting-edge serverless technology, Vercel empowers developers to create high-performance websites that can withstand any traffic spike. Let’s explore the features and benefits that Vercel offers.

Features

Zero Config, More Innovation

Vercel eliminates the need for time-consuming and unnecessary processes that slow down development. It allows developers to focus on their creativity and build when inspiration strikes. With its zero config approach, developers can get started quickly without the hassle of complex configurations.

Always Fast, Always Online

Infrastructure plays a crucial role in delivering a fast and reliable web experience. Vercel ensures that websites built on its platform are always fast and always online, providing a seamless user experience.

Dynamic Pages, Static Speed with Edge Functions

Vercel’s Edge Functions enable developers to create dynamic pages while maintaining static speed. This powerful feature allows for a more interactive web experience without sacrificing performance.

The Native Next.js Platform

As the native platform for Next.js, Vercel provides developers with all the tools they need to build their websites exactly as they imagine. From automatic API handling to built-in image and performance optimizations, Next.js on Vercel offers a complete toolkit for web development.

Real-Time Insights with Analytics

Understanding user behavior and website performance is crucial for improving the web experience. Vercel’s Analytics feature provides real-time insights, allowing developers to optimize their applications for peak performance.

Serverless Storage for the Frontend

Storing and managing frontend assets can be a challenging task. Vercel offers serverless storage, allowing developers to easily store and retrieve assets for their websites without the need for complex server configurations.

Integration with Backend and End-to-End Testing

Vercel seamlessly integrates with any data source, headless CMS, or API, making it easy to connect your website to your backend systems. Additionally, Vercel’s cloud primitives, including caching and serverless functions, work perfectly on localhost for end-to-end testing and debugging.

Collaborative Development with Preview Deployments

Frontend development is a collaborative process, and Vercel enhances this collaboration with automatic Preview Deployments. Every code change triggers a new live preview site that can be shared with the team for real-time feedback and review. Integrations with platforms like GitHub, GitLab, and Bitbucket make this process seamless.

Optimized for Performance and SEO

Speed and SEO go hand in hand when it comes to delivering a delightful user experience. Next.js and Vercel work together to ensure the best performance for end users while maintaining best-in-class SEO practices.

Global Edge Network and Guaranteed Uptime

Vercel deploys content around the world, ensuring fast access for users regardless of their location. With its global edge network, updates to your website are propagated within 300ms. Additionally, Vercel offers first-party monitoring and observability, allowing developers to analyze logs, understand traffic and usage, and easily optimize their applications.

Begin Your Vercel Journey

Importing an existing project from a Git repository is made easy with Vercel. Simply select your preferred Git provider, such as GitHub, GitLab, or Bitbucket, and import your project seamlessly. Alternatively, you can choose to clone a template from popular frameworks like Next.js, SvelteKit, Nuxt.js, or Vite to jumpstart your project.

Conclusion

Vercel’s frontend cloud provides the ideal environment for developers to build a faster, more personalized web. With its powerful features, easy integration with backend systems, and collaborative development workflows, developers can create high-performance websites that delight every visitor. Begin your Vercel journey today and experience the future of web development.

Tags: frontend, web development, Vercel, Next.js, performance

[#success]