Posts

Showing posts from 2022

Inlined images in Next.js

Image
The slowest part of loading a web page is almost always user network. If you have small images like an app logo that you don't want to wait for on network, one tool in your toolbox is to inline these images using base64 encoding. This is how inlined images look in a browser: Desired usage Our goal is to be able to write the following if we want to have an inlined image: import logo from 'images/app-logo.inline.png' and the following for the regular URL (notice the .inline. part of the file name): import logo from 'images/app-logo.png' It can be later used as usual via: <Image src={logo}/> Implementation How do we do this in Next.js? We have to add url-loader to package.json and tweak next.config.js . // next.config.js module.exports = { // ... webpack: (config) => { // find the built-in loader const imageLoaderRule = config.module.rules.find( (rule) => rule.loader === 'n

Migration locks for TypeORM

Image
Schema migrations is a must-have functionality for any DB framework. TypeORM provides decent utilities for dealing with migrations, however having a decade of experience in Ruby on Rails I got really spoiled and take some features for granted. One of these features is locking a database while a migration going on so 2 processes running concurrently don't step on each other's toes. This is also important when you run migrations in Kubernetes before launching your app. I was really surprised to find out that this basic feature is not supported , so decided to implement it on my own. Implementation // typeormMigrationUtils.ts import { Connection, createConnection } from 'typeorm' import config from '../ormconfig' import CRC32 from 'crc-32' const MIGRATOR_SALT = 2053462845 async function withAdvisoryLock( connection: Connection, callback: () => Promise<void> ): Promise<boolean> { // generate a unique lock

Using image loader is Next.js

Image
Next.js has managed to kill off create-react-app and despite new rivals (in the face of Remix) is a de-facto way to start new React apps. One of the awesome features that Next.js and its platform Vercel provides is a way to automatically optimize images for different screens to make both user and developer experience much smoother. However, if your app has any non-trivial number of images that are generated by users you may soon end up visiting Vercel's limits page . Turns out that even on Hobby and Pro plans you are limited to 1000 and 5000 images per month, any overage is going to cost you dearly. At this point, you are going to start shopping for alternative image optimization solutions. You can either host your own via Thumbor or imgproxy or use one of the hosted solutions like Cloudinary . Regardless of what service you choose, it needs to be integrated into Next.js. After taking a look at Cloudinary as an example, even their free plan o