<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by WarsawJS on Medium]]></title>
        <description><![CDATA[Stories by WarsawJS on Medium]]></description>
        <link>https://medium.com/@warsawjs?source=rss-3000a5f52ac8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7YvRf5_-i8VCJwGL-_zHxg.png</url>
            <title>Stories by WarsawJS on Medium</title>
            <link>https://medium.com/@warsawjs?source=rss-3000a5f52ac8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 04:13:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@warsawjs/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[HTML Forms: The Unsung Heroes of Web Development]]></title>
            <link>https://medium.com/warsawjs/html-forms-the-unsung-heroes-of-web-development-539eaa231454?source=rss-3000a5f52ac8------2</link>
            <guid isPermaLink="false">https://medium.com/p/539eaa231454</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[community]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[learn-ai-programming]]></category>
            <dc:creator><![CDATA[WarsawJS]]></dc:creator>
            <pubDate>Sat, 19 Apr 2025 09:41:22 GMT</pubDate>
            <atom:updated>2025-04-19T09:41:22.214Z</atom:updated>
            <content:encoded><![CDATA[<p>In the JavaScript-dominated landscape of modern web development, we often reach for complex libraries and frameworks to solve what might be simple problems. One of the most overlooked built-in features of the web platform is the humble HTML form. As highlighted by Vladyslav Chychuzhko in his lightning talk at WarsawJS Meetup #121, forms aren’t just relics of the past — they’re powerful tools with native functionality that can reduce our reliance on JavaScript while improving accessibility and user experience.</p><figure><img alt="The photo shows Vladyslav Chychuzhko standing in front of a table, holding a microphone. He is wearing a green T-shirt and a dark, patterned jacket. In the background is a laptop and a bottle of water. The wall is light in color, and the lighting gives the atmosphere a slightly blue hue, creating a modern feel. The man appears to be in the middle of a presentation or lecture." src="https://cdn-images-1.medium.com/max/1024/1*bKCS2iT5iah4BptkxsMrwA.jpeg" /><figcaption><strong>Vladyslav Chychuzhko at WarsawJS Meetup #121 at Freespace in December 2024</strong></figcaption></figure><h3>Introduction</h3><p>When building interactive web applications, developers often instinctively reach for JavaScript-heavy solutions. We implement custom form handling, validation, and submission logic from scratch, frequently reinventing capabilities already built into browsers. This approach not only increases bundle size and complexity but can also create accessibility issues when native behaviors are overridden.</p><p>As Vladyslav Chychuzhko eloquently put it in his presentation: browsers and the W3C community have done “a really great job on delivering fantastic functionality and integration” for forms. So why aren’t we taking advantage of it?</p><h3>Key Takeaways from “Form is Your Friend”</h3><h3>1. Native Form Validation Reduces JavaScript Overhead</h3><p>Modern browsers provide robust form validation capabilities without requiring a single line of JavaScript. These native validations are not only performance-optimized but also accessible by default.</p><h3>2. Forms Enhance Accessibility</h3><p>Native form elements are designed with accessibility in mind. They work seamlessly with screen readers, support keyboard navigation, and provide clear feedback to users with disabilities. Custom form implementations often miss these crucial aspects.</p><h3>3. Progressive Enhancement Is Still Relevant</h3><p>Using HTML forms as the foundation allows us to build applications that work even when JavaScript fails or is disabled. We can then enhance functionality with JavaScript where necessary, providing a more resilient user experience.</p><h3>4. Many “Modern” Features Are Already Supported</h3><p>Several form features that developers often recreate with JavaScript — like advanced input types, validation patterns, and form submission behavior — have been part of the HTML specification for years.</p><h3>Technical Details: Leveraging Native Form Capabilities</h3><p>Let’s explore some powerful form features you might not be using:</p><h3>Input Types for Automatic Validation</h3><pre>&lt;!-- Rather than custom validation for email --&gt;<br>&lt;input type=&quot;email&quot; required&gt;<br><br>&lt;!-- Built-in validation for numbers with constraints --&gt;<br>&lt;input type=&quot;number&quot; min=&quot;1&quot; max=&quot;100&quot; step=&quot;1&quot;&gt;<br><br>&lt;!-- Date pickers without JavaScript libraries --&gt;<br>&lt;input type=&quot;date&quot;&gt;<br><br>&lt;!-- URL validation --&gt;<br>&lt;input type=&quot;url&quot;&gt;</pre><p>These input types not only validate user input but also provide specialized UI on supporting browsers (e.g., date pickers and numeric keyboards on mobile).</p><h3>Pattern Validation with Regular Expressions</h3><p>Need more specific validation rules? The pattern attribute accepts regular expressions:</p><pre>&lt;!-- Validate a US phone number format --&gt;<br>&lt;input<br>  type=&quot;tel&quot;<br>  pattern=&quot;[0-9]{3}-[0-9]{3}-[0-9]{4}&quot;<br>  title=&quot;Phone format: XXX-XXX-XXXX&quot;<br>/&gt;</pre><p>The title attribute provides a tooltip explaining the expected format to users.</p><h3>Custom Validation Messages</h3><p>Want to customize validation messages? You can do that, too:</p><pre>const emailInput = document.querySelector(&#39;input[type=&quot;email&quot;]&#39;);<br><br>emailInput.addEventListener(&#39;invalid&#39;, (event) =&gt; {<br>  // Prevent the browser&#39;s default error message<br>  event.preventDefault();<br>  <br>  if (emailInput.validity.valueMissing) {<br>    emailInput.setCustomValidity(&#39;Please enter your email address&#39;);<br>  } else if (emailInput.validity.typeMismatch) {<br>    emailInput.setCustomValidity(&#39;Please enter a valid email address&#39;);<br>  } else {<br>    emailInput.setCustomValidity(&#39;&#39;);<br>  }<br>});</pre><h3>Form Submission and FormData API</h3><p>The FormData API makes collecting and processing form data straightforward:</p><pre>document.querySelector(&#39;form&#39;).addEventListener(&#39;submit&#39;, async (event) =&gt; {<br>  event.preventDefault();<br>  <br>  const form = event.target;<br>  const formData = new FormData(form);<br><br>  // Convert FormData to a plain object if needed<br>  const formValues = Object.fromEntries(formData.entries());<br>  console.log(formValues);<br><br>  // Or use directly with fetch<br>  try {<br>    const response = await fetch(form.action, {<br>      method: form.method,<br>      body: formData<br>    });<br>    <br>    if (response.ok) {<br>      const result = await response.json();<br>      // Handle successful submission<br>    }<br>  } catch (error) {<br>    // Handle errors<br>  }<br>});</pre><p>As Vladyslav Chychuzhko emphasized in his talk, forms “can and should be used in web, with no fear, at least for the sake of accessibility.” By leveraging the native capabilities of HTML forms, we can create more accessible, performant, and resilient web applications.</p><p>This doesn’t mean abandoning JavaScript entirely. Rather, it means using JavaScript to enhance native functionality instead of replacing it. This approach — known as progressive enhancement — ensures our applications work for all users, regardless of their device capabilities or accessibility needs.</p><p>Next time you’re building a form, consider starting with HTML’s native features before reaching for a JavaScript-heavy solution. You might be surprised at how much you can accomplish with less code and better accessibility.</p><h3>Next Steps</h3><ol><li><strong>Audit your existing forms</strong> to identify opportunities to replace custom JavaScript with native HTML functionality.</li><li><strong>Explore the HTML Living Standard</strong> to discover form features you might not know about.</li><li><strong>Test your forms with assistive technologies</strong> to ensure they’re truly accessible.</li><li><strong>Consider adopting a progressive enhancement approach</strong> for your next web project.</li></ol><p>By embracing HTML forms as friends rather than adversaries, we can build better web experiences for everyone.</p><p><em>This blog post was inspired by Vladyslav Chychuzhko’s lightning talk at WarsawJS Meetup #121 on December 11, 2024. You can find more about Vladyslav on </em><a href="https://www.linkedin.com/in/vladyslav-chychuzhko/"><em>LinkedIn</em></a><em>, </em><a href="https://github.com/vchychuzhko/"><em>GitHub</em></a><em>, and </em><a href="https://www.instagram.com/vchychuzhko/"><em>Instagram</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=539eaa231454" width="1" height="1" alt=""><hr><p><a href="https://medium.com/warsawjs/html-forms-the-unsung-heroes-of-web-development-539eaa231454">HTML Forms: The Unsung Heroes of Web Development</a> was originally published in <a href="https://medium.com/warsawjs">WarsawJS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bridging Mathematics and Programming: Professor Andrzej Blikle’s Lingua Project]]></title>
            <link>https://medium.com/warsawjs/bridging-mathematics-and-programming-professor-andrzej-blikles-lingua-project-d8f8c6ca16fd?source=rss-3000a5f52ac8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8f8c6ca16fd</guid>
            <category><![CDATA[community-engagement]]></category>
            <category><![CDATA[book-recommendations]]></category>
            <category><![CDATA[program-language-design]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[lingua]]></category>
            <dc:creator><![CDATA[WarsawJS]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 08:45:37 GMT</pubDate>
            <atom:updated>2025-04-17T08:45:37.528Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How denotational semantics can help developers write provably correct code.</em></p><p><strong>Reading time:</strong> 4min<br><strong>Event:</strong> WarsawJS Meetup #123–12 Feb 2025<br><strong>Video: </strong><a href="https://www.youtube.com/watch?v=jFgxEQK7Hd0">https://www.youtube.com/watch?v=jFgxEQK7Hd0</a></p><figure><img alt="The photo shows a scene from a WarsawJS lecture, where a man in a hat professor Andrzej Jacek Blikle presents in front of a multimedia screen. The screen displays text about language design and syntax. A group of listeners, diverse in terms of hairstyles and clothing, pay attention to the speaker. The lighting in the room is modern, and the whole scene exudes an atmosphere of scientific discussion and creativity." src="https://cdn-images-1.medium.com/max/1024/1*6XXwZcRN1BYdI9Gru9AP-w.jpeg" /><figcaption>professor Andrzej Jacek Blikle at WarsawJS Meetup at BEC Poland on 14th of February 2025</figcaption></figure><h3>Why This Matters</h3><blockquote>“Mathematics is the silent architect of reliable software.”<em> — Prof. Andrzej Blikle</em></blockquote><p>Modern JavaScript apps juggle state, concurrency, and ever‑growing code bases. Bugs hide in the cracks. Prof. Blikle’s <strong>Lingua</strong> project re‑introduces a forgotten super‑power — denotational semantics — to give us mathematical guarantees <em>before</em> we ship.</p><h3>1. Denotational Semantics in Plain English</h3><ul><li><strong>Operational semantics</strong> says <strong>how</strong> code runs (step by step).</li><li><strong>Denotational semantics</strong> says <strong>what</strong> code <em>means</em> (its mathematical “denotation”).</li></ul><p>By modelling a language <em>mathematically first</em>, we can <strong>prove</strong> properties (e.g., “this function never throws”) and eliminate whole classes of bugs.</p><h3>2. From Paper to Production: What Lingua Provides</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afce7ea123222f70c188c10b515c6879/href">https://medium.com/media/afce7ea123222f70c188c10b515c6879/href</a></iframe><p>For JavaScript, this can tame tricky areas such as type coercion, hoisting, and async flows.</p><h3>3. Open Collaboration Invitation</h3><p>The entire method lives in Prof. Blikle’s free e‑book <strong>“A Denotational Engineering of programming languages.”</strong> <a href="https://moznainaczej.com.pl/Download/DenotationalEngineering/AJB,%20PCh,%20JJ,%20AT%20-%20A%20Denotational%20Engineering%202024%2011%2021.pdf">Grab it here.</a></p><p>WarsawJS Community Members can contribute examples, tooling, or even a JS dialect that embeds Lingua’s guarantees.</p><h3>Key Benefits for Developers</h3><ul><li><strong>Sharper intuition</strong> for types, state, and effects.</li><li><strong>Cleaner, composable abstractions</strong> backed by proofs.</li><li><strong>Future‑proof skills</strong> as formal methods enter mainstream tooling (think TypeScript × TLA+).</li></ul><h3>Acknowledgements</h3><p>WarsawJS #123 was proudly sponsored by <strong>BEC Poland</strong>, <strong>CampusAI</strong>, and <strong>Xfaang</strong>, with media support from <strong>K MAG Magazine</strong> and tooling by <strong>JetBrains</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8f8c6ca16fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/warsawjs/bridging-mathematics-and-programming-professor-andrzej-blikles-lingua-project-d8f8c6ca16fd">Bridging Mathematics and Programming: Professor Andrzej Blikle’s Lingua Project</a> was originally published in <a href="https://medium.com/warsawjs">WarsawJS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Scenes: How Push Notifications Scale to Millions of Users]]></title>
            <link>https://medium.com/warsawjs/behind-the-scenes-how-push-notifications-scale-to-millions-of-users-4651289e9d00?source=rss-3000a5f52ac8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4651289e9d00</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[warsawjs]]></category>
            <category><![CDATA[vonage]]></category>
            <category><![CDATA[meetup]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[WarsawJS]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 19:08:16 GMT</pubDate>
            <atom:updated>2025-04-16T19:08:16.910Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Buzz. Ding. Pop. The sounds of our daily digital life have become so commonplace we hardly notice them anymore — until they stop, that is. Push notifications have become the invisible backbone of our connected experience, delivering everything from breaking news to chat messages, appointment reminders to security alerts.</p><p>But have you ever stopped to wonder what happens behind the scenes to make those little alerts appear on your screen? As <strong>Avital Tzubeli</strong> shared in <a href="https://www.youtube.com/watch?v=JYakuAo_Kdo">her WarsawJS presentation</a>, the scale is mind‑boggling: <strong>16 million notifications per day</strong>, all racing against time, load, and latency to reach their destination.</p><p>In this article, we’ll dive into the fascinating world of push‑notification infrastructure, exploring how companies like Vonage build scalable message buses using Node.js, RabbitMQ, and intelligent auto‑scaling to keep those notifications flowing reliably.</p><figure><img alt="The image shows two participants in the WarsawJS online meeting, with the event logo in the background. On the left is a man with short hair, wearing a gray sweater, with a serious expression on his face. On the right, a woman with long hair, wearing headphones, smiles at the camera, which gives the atmosphere a friendly and interactive mood. At the bottom of the screen, the participants interact in the form of a chat." src="https://cdn-images-1.medium.com/max/1024/1*_qqDTFHaGEIxUmI873piSg.jpeg" /><figcaption>Piotr and Avital during WarsawJS Meetup #78</figcaption></figure><h3>Key Takeaways from the Presentation</h3><h3>1. The Scale Challenge</h3><p>Push notifications operate at an astonishing scale. For a communications platform like Vonage, delivering 16 million notifications daily means their systems must process:</p><ul><li><strong>185 notifications per second</strong> (average)</li><li><strong>Thousands per second</strong> during peak hours</li><li>Destinations in virtually every country and time zone</li></ul><p>This scale presents unique challenges around:</p><ul><li><strong>Reliability</strong> — every notification must reach its destination</li><li><strong>Speed</strong> — users expect near‑instantaneous delivery</li><li><strong>Resilience</strong> — the system can’t fail during traffic spikes</li></ul><h3>2. The Message‑Bus Architecture</h3><p>At the core of any notification system is a message bus — essentially a highly optimized traffic controller for data. Vonage’s implementation uses a combination of:</p><ul><li><strong>Node.js</strong> for the service layer</li><li><strong>RabbitMQ</strong> as the message broker</li><li><strong>Auto‑scaling</strong> infrastructure to handle load fluctuations</li><li><strong>Monitoring systems</strong> that track performance and failures</li></ul><h3>3. The Role of Monitoring and Alerting</h3><p>Sophisticated monitoring is essential for maintaining a high‑performance notification system. Comprehensive telemetry helps:</p><ul><li>Predict traffic patterns</li><li>Identify bottlenecks before they impact users</li><li>Alert teams to unusual behavior that might indicate issues</li><li>Provide data for continuous improvement</li></ul><h3>Technical Implementation Details</h3><p>Below is a simplified example of how you might build a scalable notification pipeline.</p><h3>Setting Up a Basic Message Queue with Node.js and RabbitMQ</h3><p>producer.js — the service that creates notifications:</p><pre>// producer.js<br>const amqp = require(&#39;amqplib&#39;);<br><br>async function sendNotification(userId, message, priority) {<br>  try {<br>    const connection = await amqp.connect(&#39;amqp://localhost&#39;);<br>    const channel = await connection.createChannel();<br><br>    const queue = &#39;notifications&#39;;<br>    await channel.assertQueue(queue, { durable: true });<br><br>    const notification = {<br>      userId,<br>      message,<br>      timestamp: new Date().toISOString(),<br>      priority<br>    };<br><br>    channel.sendToQueue(queue, Buffer.from(JSON.stringify(notification)), {<br>      persistent: true<br>    });<br><br>    console.log(`✅ Notification queued for user ${userId}`);<br><br>    setTimeout(() =&gt; connection.close(), 500);<br>  } catch (error) {<br>    console.error(&#39;Failed to send notification:&#39;, error);<br>  }<br>}</pre><p>consumer.js — the service that delivers notifications:</p><pre>// consumer.js<br>const amqp = require(&#39;amqplib&#39;);<br><br>async function startConsumer() {<br>  try {<br>    const connection = await amqp.connect(&#39;amqp://localhost&#39;);<br>    const channel = await connection.createChannel();<br><br>    const queue = &#39;notifications&#39;;<br>    await channel.assertQueue(queue, { durable: true });<br>    channel.prefetch(1);<br><br>    console.log(&#39;🔄 Notification consumer waiting for messages…&#39;);<br><br>    channel.consume(queue, async (msg) =&gt; {<br>      if (!msg) return;<br><br>      const notification = JSON.parse(msg.content.toString());<br><br>      try {<br>        await sendToDevice(notification);<br>        channel.ack(msg);<br>        console.log(`✅ Delivered notification to user ${notification.userId}`);<br>      } catch (error) {<br>        channel.reject(msg, true); // requeue for retry<br>        console.error(`❌ Failed to deliver notification: ${error.message}`);<br>      }<br>    });<br>  } catch (error) {<br>    console.error(&#39;Consumer error:&#39;, error);<br>  }<br>}<br><br>async function sendToDevice(notification) {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>      Math.random() &gt; 0.05 ? resolve() : reject(new Error(&#39;Device unreachable&#39;));<br>    }, 50);<br>  });<br>}<br><br>startConsumer();</pre><h3>Implementing Auto‑Scaling</h3><p>A lightweight worker‑scaling manager:</p><pre>// worker-manager.js<br>const { exec } = require(&#39;child_process&#39;);<br><br>class WorkerManager {<br>  constructor(queueUrl, minWorkers = 2, maxWorkers = 10) {<br>    this.queueUrl = queueUrl;<br>    this.minWorkers = minWorkers;<br>    this.maxWorkers = maxWorkers;<br>    this.currentWorkers = 0;<br>    this.workers = new Map();<br>  }<br><br>  async initialize() {<br>    for (let i = 0; i &lt; this.minWorkers; i++) await this.startWorker();<br>    setInterval(() =&gt; this.adjustWorkerCount(), 30_000);<br>  }<br><br>  async getQueueMetrics() {<br>    // Replace with real metrics from RabbitMQ<br>    return {<br>      messageCount: Math.floor(Math.random() * 10_000),<br>      consumerCount: this.currentWorkers,<br>      avgProcessingTime: 50 + Math.random() * 20<br>    };<br>  }<br><br>  async adjustWorkerCount() {<br>    const { messageCount } = await this.getQueueMetrics();<br>    const target = Math.ceil(messageCount / (100 * 5));<br>    const desired = Math.max(this.minWorkers, Math.min(target, this.maxWorkers));<br><br>    if (desired &gt; this.currentWorkers) {<br>      console.log(`Scaling up to ${desired} workers`);<br>      for (let i = this.currentWorkers; i &lt; desired; i++) await this.startWorker();<br>    } else if (desired &lt; this.currentWorkers) {<br>      console.log(`Scaling down to ${desired} workers`);<br>      for (let i = this.currentWorkers; i &gt; desired; i--) await this.stopWorker();<br>    }<br>  }<br><br>  async startWorker() {<br>    const id = Date.now().toString(36) + Math.random().toString(36).slice(2);<br>    const proc = exec(`node consumer.js ${this.queueUrl} ${id}`);<br>    this.workers.set(id, proc);<br>    this.currentWorkers++;<br>    console.log(`Started worker ${id}. Total: ${this.currentWorkers}`);<br>  }<br><br>  async stopWorker() {<br>    if (this.currentWorkers &lt;= this.minWorkers) return;<br>    const [id] = this.workers.keys();<br>    this.workers.get(id).kill(&#39;SIGTERM&#39;);<br>    this.workers.delete(id);<br>    this.currentWorkers--;<br>    console.log(`Stopped worker ${id}. Total: ${this.currentWorkers}`);<br>  }<br>}<br><br>new WorkerManager(&#39;amqp://localhost&#39;).initialize().catch(console.error);</pre><h3>Implementing Monitoring</h3><p>A minimal Prometheus metrics endpoint:</p><pre>// monitoring.js<br>const promClient = require(&#39;prom-client&#39;);<br>const express = require(&#39;express&#39;);<br>const amqp = require(&#39;amqplib&#39;);<br><br>const register = new promClient.Registry();<br>promClient.collectDefaultMetrics({ register });<br><br>const notificationsSent = new promClient.Counter({<br>  name: &#39;notifications_sent_total&#39;,<br>  help: &#39;Total notifications sent&#39;,<br>  labelNames: [&#39;priority&#39;, &#39;status&#39;],<br>  registers: [register]<br>});<br><br>const notificationLatency = new promClient.Histogram({<br>  name: &#39;notification_latency_seconds&#39;,<br>  help: &#39;Notification delivery time&#39;,<br>  buckets: [0.05, 0.1, 0.2, 0.5, 1, 2, 5],<br>  registers: [register]<br>});<br><br>const queueSize = new promClient.Gauge({<br>  name: &#39;notification_queue_size&#39;,<br>  help: &#39;Current queue depth&#39;,<br>  registers: [register]<br>});<br><br>async function updateQueueMetrics() {<br>  try {<br>    const conn = await amqp.connect(&#39;amqp://localhost&#39;);<br>    const ch = await conn.createChannel();<br>    const q = await ch.assertQueue(&#39;notifications&#39;);<br>    queueSize.set(q.messageCount);<br>    await conn.close();<br>  } catch (err) {<br>    console.error(&#39;Queue‑metrics update failed:&#39;, err);<br>  }<br>}<br><br>setInterval(updateQueueMetrics, 15_000);<br><br>express()<br>  .get(&#39;/metrics&#39;, async (_, res) =&gt; {<br>    res.set(&#39;Content-Type&#39;, register.contentType);<br>    res.end(await register.metrics());<br>  })<br>  .listen(9090, () =&gt; console.log(&#39;Metrics server on :9090&#39;));<br><br>module.exports = {<br>  recordNotificationSent: (priority, status) =&gt;<br>    notificationsSent.inc({ priority, status }),<br>  recordLatency: (seconds) =&gt; notificationLatency.observe(seconds)<br>};</pre><h3>Conclusion</h3><p>Push notifications might seem simple on the surface, but building a system that reliably delivers millions of messages every day demands sophisticated architecture, careful monitoring, and intelligent scaling. As Avital Tzubeli demonstrated, combining Node.js, RabbitMQ, and cloud auto‑scaling offers a powerful foundation.</p><h3>Key Lessons</h3><ol><li><strong>Design for resilience from the start</strong> — assume components will fail.</li><li><strong>Implement comprehensive monitoring</strong> — you can’t fix what you can’t measure.</li><li><strong>Use message queues to decouple systems</strong> — for scalability and fault tolerance.</li><li><strong>Auto‑scale based on real‑time metrics</strong> — react automatically to load changes.</li><li><strong>Prioritize messages appropriately</strong> — not every alert is equally urgent.</li></ol><p>As our digital lives grow ever more notification‑driven, understanding these architectures gives developers invaluable insights into building any high‑scale, reliable messaging system.</p><p>Whether you’re building the next communications platform or “just” adding notifications to your app, these patterns will help you create resilient, scalable systems that keep users informed without missing a beat.</p><p><em>Have you implemented push notifications in your applications? What challenges did you face with scaling? Share your experiences in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4651289e9d00" width="1" height="1" alt=""><hr><p><a href="https://medium.com/warsawjs/behind-the-scenes-how-push-notifications-scale-to-millions-of-users-4651289e9d00">Behind the Scenes: How Push Notifications Scale to Millions of Users</a> was originally published in <a href="https://medium.com/warsawjs">WarsawJS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS in JS in real-life]]></title>
            <link>https://medium.com/warsawjs/css-in-js-in-real-life-e0b50bbbd740?source=rss-3000a5f52ac8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0b50bbbd740</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[jsx]]></category>
            <dc:creator><![CDATA[WarsawJS]]></dc:creator>
            <pubDate>Fri, 20 Jul 2018 11:38:08 GMT</pubDate>
            <atom:updated>2018-08-19T13:59:46.492Z</atom:updated>
            <content:encoded><![CDATA[<p>By <a href="https://medium.com/u/5fd4e1434f16">Artur Siery</a></p><p>Recently I have stumbled across a lot of blog posts describing changes in <a href="https://medium.com/actualize-network/modern-css-explained-for-dinosaurs-5226febe3525">styling</a> <a href="https://medium.freecodecamp.org/css-in-javascript-the-future-of-component-based-styling-70b161a79a32">approaches</a>. Clearly, we’re entering a new era of styling in JS, that simply can be called <em>CSS in JS</em>. But what all of those posts miss, in my opinion, is a deep comparison of the features provided by those solutions and how they perform in real-world project. Code examples always look fresh and reusable and sexy, but what happens when we pick such solution and use it in a live application? Are there any drawbacks that turn beautiful ideas into coding hell? Let’s find out.</p><blockquote>Side note: Recently I’ve been a React developer and when I did the research I was focusing mainly on how I could utilize the technology in my projects, so therefore I will mostly focus on the ease of use in React. Ability to read JSX will help you to understand what the heck is going on.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fkyv3GKuzxfqE_7f8cdxIw.jpeg" /></figure><h3>CSS Modules</h3><p>Putting <a href="https://github.com/css-modules/css-modules">CSS Modules</a> here can be a bit of a stretch, depending on how you define CSS in JS, because you write basically in CSS (with some cool additions). What’s change is the way of loading the styles into components. But they were the first, so treat it like a honorable mention on the list. Chances are that you probably seen CSS Modules somewhere. But let’s take a look at them (or, you know, you can always scroll to the next section). Let’s start with this simple example:</p><pre>// styles.css<br>.heading {<br>  color: gray;<br>  font-size: 1.5em;<br>}</pre><pre>.paragraph {<br>  font-size: 1.1em;<br>}</pre><pre>// component.js<br>import React from &#39;react&#39;;<br>import styles from &#39;./styles.css&#39;;</pre><pre>const Article = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1 className={styles.heading}&gt;<br>        Heading<br>      &lt;/h1&gt;<br>      &lt;p className={styles.paragraph}&gt;<br>        Article&#39;s text<br>      &lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Okay, so as you can see, the CSS are still the same. You simply write them like you did for years. What changes is the way of loading them into your application. Now, while bundling, the CSS files are being parsed and turn into pure JS objects, that are easy to use inside code. Styles are imported explicitly and used like any other JS object, which is very cool from the semantic perspective. But that’s not where CSS Modules shine.</p><h4>Local Scope</h4><p>Having classnames parsed, CSS Modules is able to change the names of the output classnames into totally unique strings. This gives us local scope inside CSS. That’s huge! The generated output will look like this:</p><pre>// output<br>&lt;div&gt;<br>  &lt;h1 class=&quot;6b87a4&quot;&gt;Heading&lt;/h1&gt;<br>  &lt;p class=&quot;7h3g1a&quot;&gt;Article&#39;s text&lt;/p&gt;<br>&lt;/div&gt;</pre><p>The unique classnames are awesome! Are the solution to everything! And are totally un-debuggable. But there’s a small fix for it:</p><pre>// fix (in webpack.config.js)<br>(...)&amp;localIdentName=[path]_[name]_[local]_[hash:base64:5]</pre><pre>// output<br>&lt;div&gt;<br>  &lt;h1 class=&quot;src-components_component_heading_6b87a4&quot;&gt;<br>    Heading<br>  &lt;/h1&gt;<br>  &lt;p class=&quot;src-components_component_paragraph_7h3g1a&quot;&gt;<br>    Article&#39;s text<br>  &lt;/p&gt;<br>&lt;/div&gt;</pre><p>Ah, much better! Now it’s clearly visible what styles come from what files. You can adjust the naming convention according to what’s suits you the most.</p><p>Pros:</p><ul><li>Pure CSS (no learning curve)</li><li>Some additional features</li><li>Local scoping</li><li>Nice semantics using JavaScript’s import statement</li><li>Easy debugging (with the right Webpack setting)</li></ul><p>Cons:</p><ul><li>No more global styles, which is generally a good thing, but you need to invest some time to adjust to this approach</li><li>Additional Webpack (or other bundler) configuration</li></ul><h4>SASS Modules / LESS Modules</h4><p>CSS Modules on their own bring some additional functionalities, like <em>composition </em>or <em>global pseudo class</em>. But if you’re missing some of the cool stuff like <em>mixins</em> or <em>variables</em> you can always add <a href="https://sass-lang.com/">SASS</a> or <a href="http://lesscss.org/">LESS</a>. Just add the respective loader to your webpack config. Now, you have a very powerful duo, fully pack with features and possibilities.</p><p>Pros:</p><ul><li>All of the CSS Modules features</li><li>All of the SASS/LESS features (!)</li></ul><p>Cons:</p><ul><li>Similar as CSS Modules</li></ul><blockquote>For a long time I thought that using SASS with CSS Modules was the ultimate solution. Then, the other solutions came along.</blockquote><h3>Styled Components</h3><p>Although one can argue, that CSS Modules were the first CSS in JS, <a href="https://github.com/styled-components/styled-components">Styled Components</a> were the one that started the whole avalanche of such solutions recently.</p><p>Styled Components utilize tagged template strings and allow to put your CSS code inside JavaScript directly. You can still split it into 2 files, to get that feeling of logic and styles being separate. But it’s optional. So, how our example would look like in Styled Components? Let’s see:</p><pre>// component.js<br>import React from &#39;react&#39;;<br>import styled from &#39;styled-components&#39;;</pre><pre>const Heading = styled.h1`<br>  color: gray;<br>  font-size: 1.5em;<br>`;</pre><pre>const Paragraph = styled.p`<br>  font-size: 1.1em;<br>`;</pre><pre>const Article = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;Heading&gt;<br>        Heading<br>      &lt;/Heading&gt;<br>      &lt;Paragraph&gt;<br>        Article&#39;s text<br>      &lt;/Paragraph&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>It’s pretty straightforward. Just use tags provided by the library to render a component that you would like having styling added to inside the template string literal. As simple as that.</p><h4>Extending styles</h4><p>Let’s say, we would like to extend the styling of existing component and add some more. That’s very simple:</p><pre>const SexyParagraph = styled(Paragraph)`<br>  text-decoration: underline;<br>  color: green;<br>`;</pre><p>Things get a little bit complicated, when you would like to add additional handlers to styled components. Let’s take a simple button and add a onClickhandler to it. Sadly, we can’t do it in one step. What we need to do, is basically create 2 components — one with logic, and one that brings styles:</p><pre>// button.js<br>import React from &#39;react&#39;;<br>import styled from &#39;styled-components&#39;;</pre><pre>const Button = ({ children }) =&gt; (<br>  &lt;button onClick={() =&gt; console.log(&#39;click&#39;)}&gt;{children}&lt;/button&gt;<br>);</pre><pre>const StyledButton = styled(Button)`<br>  border: solid 2px green;<br>`;</pre><pre>// usage:<br>&lt;StyledButton&gt;My fancy button&lt;/StyledButton&gt;</pre><p>So this makes things a bit excessive. Every time you would like to add some logic to a component, you will end up with 2 components. While it is kinda in style of <a href="https://reactjs.org/docs/higher-order-components.html">HoC</a>, but it just doesn’t go well with other HoC, so it can’t be used with cool HoC helpers like <a href="https://github.com/acdlite/recompose">recompose</a>. I must admit, that I’m a big fan of HoC and not being able to use Styled Components in that fashion just misses the mark for me.</p><p>Creating a separate component every time that a styling is needed seems like a good idea, but when I used such approach I suddenly missed the ability to just write a bit more complicated markup. So, in theory this approach is very appealing, but practice shows that sometimes you need to produce much more small components. This can lead to less readable code. Because if I can do something in 20 lines of JSX, I would prefer that over creating 10 small components.</p><h4>Dynamic Styles</h4><p>One of cool features of Styled Components, that was just not possible in CSS Modules, is the ability to read components’ props and generate the appropriate styling. Let’s assume that we have 2 props: important and width. They can be accessed inside the style in such manner:</p><pre>const CustomButton = styled.button`<br>  color: ${props =&gt; props.important ? &#39;red&#39; : &#39;black&#39;};<br>  width: ${props =&gt; props.width}px;<br>}</pre><pre>&lt;CustomButton important={false} width={320}&gt;My button&lt;/Button&gt;</pre><p>Dynamic styles are a pretty cool feature. Although my concern is that it can lead to more logic-heavy styles. Depending on the project, that can be a double edged sword.</p><h4>Theming</h4><p>Another great feature is theme support. That’s right, you can simply define your theme or color palette (as a simple object) and access its properties whenever you like. But what if I could tell you, that you can change themes on the fly? Yup, it’s possible. Let’s see it in action:</p><pre>// button.js<br>const ThemableButton = styled.button`<br>  color: ${props =&gt; props.theme.textColor};<br>  border: ${props =&gt; props.theme.borderColor};<br>`;</pre><pre>// themes.js<br>const theme = {<br>  textColor: &#39;red&#39;,<br>  borderColor: &#39;gray&#39;<br>};</pre><pre>const otherTheme = {<br>  ...theme,<br>  textColor: &#39;green&#39;<br>};</pre><pre>// in app.js<br>&lt;ThemeProvider theme={theme}&gt;<br>  &lt;div&gt;<br>   &lt;SomeComponent&gt;<br>     &lt;ThemableButton&gt;Red button&lt;/ThemableButton&gt;<br>   &lt;/SomeComponent&gt;<br>  &lt;/div&gt;</pre><pre>&lt;ThemeProvider theme={otherTheme}&gt;<br>    &lt;ThemableButton&gt;I&#39;m green!&lt;/ThemableButton&gt;<br>  &lt;/ThemeProvider&gt;<br>&lt;/ThemeProvider&gt;</pre><p>The usage of ThemeProvider allows to add a theme (via property) to all components inside. If you’re in need of adding another theme, just place your components inside another ThemeProvider and enter a new theme property. As simple as that. The question arises, how many times you were in need of a theming that can be changed? I didn’t see much of such projects recently, but if you need it, it’s there.</p><h4>Debugging</h4><p>Now, from debugging perspective, the generated output is fairly good. The StyledButton from the example above will not render a component inside a component, which is good. At the very beginning only the class names are unreadable (such as in case of CSS Modules). But there’s a Babel <a href="https://github.com/styled-components/babel-plugin-styled-components">plugin for that</a>, and you’re good to go.</p><p>Pros:</p><ul><li>Easy to use, easy to understand.</li><li>Local scope</li><li>Dynamic styling based on props</li><li>Theming</li><li>Easy debugging (with babel plugin)</li><li>Works with React Native (although I didn’t test that)</li></ul><p>Cons:</p><ul><li>Excessive creation of components (2 components each time handler or lifecycle method needs to be used)</li><li>Possible too much of too small components</li><li>Syntax highlighting needs an external plugin</li></ul><h3>Glamorous</h3><p><a href="https://glamorous.rocks/">Glamorous</a> takes inspiration from Styled Components and aims to change a bit the way you can use it. Notably, the biggest difference is the departure from tagged template strings in favor of plain objects. You still would use it in a similar way, but replacing string with objects. Just take a look:</p><pre>import glamorous from &#39;glamorous&#39;;</pre><pre>const Heading = glamorous.h1({<br>  fontSize: &#39;2.4em&#39;,<br>  marginTop: 10,<br>  color: &#39;#CC3A4B&#39;<br>})</pre><pre>// rendering<br>render() {<br>  return (&lt;Heading&gt;My Heading&lt;/Heading&gt;);<br>}</pre><p>To use media queries, pseudo classes and pseudo elements, simply create nested objects with selectors as their names, like so:</p><pre>import glamorous from &#39;glamorous&#39;;</pre><pre>const Heading = glamorous.h1({<br>  fontSize: &#39;2.4em&#39;,<br>  marginTop: 10,<br>  color: &#39;#CC3A4B&#39;,<br>  <br>  &#39;:hover&#39;: {<br>    color: &#39;yellow&#39;<br>  }</pre><pre>&#39;@media only screen and (max-width: 500px)&#39;: {<br>    marginTop: 5,<br>    fontSize: &#39;1.8em&#39;<br>  }<br>});</pre><pre>// rendering<br>render() {<br>  return (&lt;Heading&gt;My Heading&lt;/Heading&gt;);<br>}</pre><h4>Animations</h4><p>Well, this is something that does not come with Styled Components. Glamorous has a build in helper for creating CSS animations. That’s something really cool. Nowadays fluid animations and transitions are important parts of good UX and everything that improves creation of those effects is more then welcome.</p><pre>const AnimatedDiv = glamorous.div((props) =&gt; {<br>  const bounce = glamor.css.keyframes({<br>    &#39;0%&#39;: { transform: `scale(1.01)` },<br>    &#39;100%&#39;: { transform: `scale(0.99)` }<br>  })</pre><pre>return {<br>    animation: `${bounce} 0.2s infinite alternate`<br>  }<br>});</pre><p>Okay, so it’s not a game changing functionality. But it allows to create unique keyframes animations in a simple manner.</p><h4>Dynamic Styling</h4><p>Just like in Styled Components, Glamorous has the ability to use dynamic styling. In my opinion, it does it in much clearer way. Because we work with objects, not with string literals, conditional operations are much more natural. Simply, instead of object, pass a function that receives props and returns a valid object.</p><pre>const CustomButton = glamorous.button((props) =&gt; ({<br>  color: props.important ? &#39;red&#39; : &#39;black&#39;,<br>  width: props.width<br>});</pre><pre>&lt;CustomButton important={false} width={320}&gt;My button&lt;/Button&gt;</pre><p>Obviously, having the ability to pass a function into the component factory gives you much more flexibility, but allows to create even more logic-heavy styles. Double edged sword once again.</p><h4>Theming and reusing styles</h4><p>Theming for Glamorous looks like it was taken directly from Styled Components, just define a theme object and pass it to your components. They will have access to it via props.theme. Simple as that.</p><p>Glamorous allows also to reuse and extend existing styles. For that you can use the glamorous object as a function, pass the component and then styles to override the existing ones.</p><pre>const GreatButton = glamorous(CustomButton)({<br>  padding: 20<br>});</pre><p>Moreover, it allows you to copy existing styles to a different tag via withComponent method:</p><pre>const GreatLink = GreatButton.withComponent(&#39;a&#39;);</pre><h4>Not HoC compliant</h4><p>When it comes to overall usage, Glamorous suffers from the same drawback of not really being in compliant with HoC approach. So, once again, to build a more advanced component with styling, you will need to create 2 components. Let’s revisit the example from Styled Components:</p><pre>// button.js<br>import React from &#39;react&#39;;<br>import glamorous from &#39;glamorous&#39;;</pre><pre>const Button = ({ children }) =&gt; (<br>  &lt;button onClick={() =&gt; console.log(&#39;click&#39;)}&gt;{children}&lt;/button&gt;<br>);</pre><pre>const StyledButton = glamorous(Button)({<br>  border: &#39;solid 2px green&#39;<br>});</pre><pre>// usage:<br>&lt;StyledButton&gt;My fancy button&lt;/StyledButton&gt;</pre><p>So this comes with the same issue: too many small components.</p><h4>Debugging</h4><p>When it comes to debugging, Glamorous on it’s own is not very readable in the DevTools. But, obviously, there’s a <a href="https://github.com/bernard-lin/babel-plugin-glamorous-displayname">plugin</a> for that.</p><p>Pros:</p><ul><li>...styledComponents.pros</li><li>Object notation instead template literals</li><li>Keyframes helper</li></ul><p>Cons:</p><ul><li>(Potentially) excessive components creation</li></ul><h3>Styletron</h3><p>When it comes to <a href="https://github.com/rtsao/styletron">Styletron</a>, I’m probably quite biased. I have become involved in a project using it and it quickly pushed me to do research on other similar solutions to migrate away to. I felt so limited and distracted by it so I couldn’t just bare with styling anymore. I get the impression, that Styletron does a lot of things similar to Glamorous, but fails to deliver really usable in real-life solution. Let’s start with basics:</p><pre>import { styled } from &#39;styletron-react&#39;;</pre><pre>const Heading = styled(&#39;h1&#39;, {<br>  fontSize: &#39;2.4em&#39;,<br>  marginTop: 10,<br>  color: &#39;#CC3A4B&#39;<br>});</pre><pre>// rendering<br>render() {<br>  return (&lt;Heading&gt;My Heading&lt;/Heading&gt;);<br>}</pre><p>When it comes to simple usage, it’s almost the same as in Glamorous.</p><h4>Themes, dynamic styles and extending styles</h4><p>Styletron provides ways to extend existing styles, or to build dynamic styles. It also supports theming in a very similar fashion, as we have seen previously. Let’s see all of those features in action together:</p><pre>import { styled } from &#39;styletron-react&#39;;<br>import ThemeProvider from &#39;./ThemeProvider&#39;;<br>import Button from &#39;./GenericButton&#39;;</pre><pre>const FancyButton = styled(GenericButton, ({ theme, size }) =&gt; {<br>  return { <br>    color: theme.button.color,<br>    background: theme.button.background,<br>    height: (size === &#39;big&#39;) ? &#39;30px&#39;, &#39;20px&#39;,<br>    width: (size === &#39;big&#39;) ? &#39;100px&#39;, &#39;60px&#39;<br>  };<br>});</pre><pre>const MyTheme = {<br>  button: {<br>    color: &#39;#ee3ae4&#39;,<br>    background: &#39;#323c4d&#39;<br>  }<br>}</pre><pre>// rendering<br>&lt;ThemeProvider theme={MyTheme}&gt;<br>  &lt;FancyButton size=&quot;big&quot;&gt;Click me&lt;/FancyButton&gt;<br>&lt;/ThemeProvider&gt;</pre><p>Similar to previous solutions, Styletron does not allow to create more lifecycle-heavy components with styles. Instead, you need to create 2 components, one with logic, and one with styles:</p><pre>class MyComponent extends React.Component {<br>  componendDidMount() {<br>    // some awesome logic here<br>  }</pre><pre>render() {<br>    return (&lt;div&gt;My Component&lt;/div&gt;)<br>  }<br>}</pre><pre>const StyledComponent = styled(MyComponent, { /* styles */ });</pre><p>So, let’s see, what Styletron renders in HTML…</p><h4>Generated output</h4><p>The output for the example above will be something like:</p><pre>&lt;div class=&quot;_c _d _g x1 x3 xm _a&quot;&gt;<br>  &lt;div&gt;<br>    My Component<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>And two issues can be seen here. Firstly, that the rendered code is totally not debuggable. You can’t really deduce from which component any of the styles really come. Or even what component you’re looking at. Switching to React DevTools doesn’t help either. All you gonna see is that it’s &lt;styled(div)&gt;. That’s really helpful.</p><p>Oh, and each style property gets it’s own, unique class name. Imagine having a well styled component with over 30 properties. Yeah…</p><pre>&lt;div class=&quot;_a _b _c _d _e _f _m1 _m2 _m3 _m4 _m17 _m20 _m22 _m33<br>            _m45 _m46 _la _lg _lz _lh _l5 _hm _hn _hi x1 x12 x13<br>            x15 x16 x21 x22 x23 x24 x25 x26 x30 x32 x33 x34&quot;&gt; <br>  Hi<br>&lt;/div&gt;</pre><p>And what’s even worse, there is <strong>no debugging plugin</strong> for it!</p><p>Moreover, imagine that the example would have 10 nested components, one inside another. Could you tell the number of generated divs? Yup, 20. Because every time you need to have more advanced component, Styletron will need to add additional wrapper for styling purposes. That’s something I like to call a <em>Wrapper-iada</em>. And it’s no good.</p><h4>Other issues</h4><p>Styletron has a bug that’s basically prevents you from using dynamic tags (so the tags used depending on the props). Let me explain:</p><pre>const headers = {<br>  h1: &#39;h1&#39;,<br>  h2: &#39;h2&#39;,<br>  h3: &#39;h3<br>}</pre><pre>const DynamicHeader = ({ size, children }) =&gt; {<br>  const Element = headers[size];</pre><pre>return (<br>    &lt;Element&gt;{children}&lt;/Element&gt;<br>  );<br>};</pre><p>Now, if I would like to add styling to my DynamicHeader, I would go with:</p><pre>const StyledHeader = styled(DynamicHeader, { /* new styles */ });</pre><p>None of the new styles won’t be applied. Why? I don’t have an idea, but it’s not good.</p><h4>No animations</h4><p>That’s right, Styletron does not support css keyframes! Obviously, you can use animation like the following:</p><pre>const BouncyDiv = styled(&#39;div&#39;, {<br>  animation: &#39;bounce 1s&#39;<br>});</pre><p>And it will work. But you can’t define the keyframes of bounce using Styletron. If you would really like to somehow define keyframes, you need to use good, ol’ CSS. That’s a terrible solution.</p><p>Let’s sum up:</p><p>Pros:</p><ul><li>Looks similar to Glamorous</li><li>Local scope</li><li>Theming, dynamic styles, extending styles</li></ul><p>Cons:</p><ul><li>Undebuggable (!)</li><li>Wrapper-iada</li><li>No dynamic elements</li><li>No keyframes support</li></ul><h3>Styled JSX</h3><p>Next CSS-in-JS solution that I researched was <a href="https://github.com/zeit/styled-jsx">Styled JSX</a>. At the very beginning it looks different to the solutions above, it kinda looks more inline with JSX approach and I find it a bit more appealing. The basic example looks like this:</p><pre>const MyComponent () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Heading&lt;/h1&gt;<br>      &lt;p&gt;Paragraph 1&lt;/p&gt;<br>      &lt;p className=&quot;p2&quot;&gt;Paragraph 2&lt;/p&gt;</pre><pre>&lt;style jsx&gt;{`<br>        h1 {<br>          font-size: 1.6em;<br>        }</pre><pre>        p {<br>          line-height: 1.5em;<br>        }</pre><pre>        .p2 {<br>          color: gray;<br>        }<br>      `}&lt;/style&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Styled JSX uses template literals inside of a &lt;style jsx&gt; tag. What’s really neat, is that you can use the plain old CSS inside. It’s readable, it’s safe due to local scope. If you like, you can move the string to a separate file because everything is in a string. If you’re running React in versions 16.2 or higher, you can replace the div with React’s fragment.</p><h4>Same features and more freedom</h4><p>Obviously, defining the styles inside component’s render method allows us to access all of the props and hence build dynamic styles. Or you can access the theme provided by ThemeProvider although you need to use additional module for that, as Styled JSX don’t have a built in ThemeProvider.</p><pre>const MyComponent ({ theme, size }) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Heading&lt;/h1&gt;</pre><pre>      &lt;style jsx&gt;{`<br>        h1 {<br>          font-size: ${size}px;<br>          color: ${theme.heading.color};<br>        }<br>      `}&lt;/style&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>What I like here, is that I can write styles and apply them to components with lifecycle methods. Another thing to like is that Styled JSX integrates nicely with React’s idea of rendering components. That was not possible with any of the previous libraries. But here I can decide when I should split component into smaller ones. That kind of freedom is something I really appreciate. Artificial code splitting forced by previous solutions does not always end up in a very readable code.</p><h4>Drawbacks</h4><p>I must say I really like this approach, but the drawbacks just kill it for me. The problems start when you want to extend existing styling. Or when you would like to alter the default styling of a child component. There is no easy way of doing such things. While in Glamorous all you needed was to call glamorous(DefaultButton)(newStyles), in Styled JSX you need to come up with your own approach to reusing existing styling. So as I said before, this kills the Styled JSX for me.</p><p>Pros:</p><ul><li>More inline with JSX approach</li><li>Doesn’t force artificial code splitting</li><li>Easy to understand</li><li>Local scope</li><li>Dynamic Styles, Themes support</li></ul><p>Cons:</p><ul><li>Reusability of styles is hard if non-existent</li></ul><h3>JSS</h3><p>The last but not least — <a href="http://cssinjs.org/">JSS</a>. At first glance, JSS looks very similar to Glamorous. You create objects literals with styles, you apply them to components. But it also successfully adds the ability to write couple styles for multiple tags inside one component.</p><pre>import withStyles from &#39;react-jss&#39;;</pre><pre>const styles = {<br>  heading: {<br>    fontSize: &#39;1.6em&#39;<br>  },<br>  paragraph: {<br>    lineHeight: &#39;1.4em&#39;<br>  }<br>};</pre><pre>const MyComponent ({ classes }) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1 className={classes.heading}&gt;<br>        Heading<br>      &lt;/h1&gt;<br>      &lt;p className={classes.paragraph}&gt;<br>         Paragraph 1<br>      &lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default withStyles(styles)(MyComponent);</pre><p>First what I have to admit, and what really got me excited about JSS is that finally, it’s a HoC! You pass a object with different class names to it, and the HoC will produce a wrapper that adds a classes property containing generated, unique class names. In a way, it brings the functionality of both Styled JSX and Glamorous neatly together. That’s off to a good start.</p><h4>Theming and dynamic styles</h4><p>Just like abovementioned solutions, JSS supports both themes and dynamic styles. It comes with build in ThemeProvider which is always a neat solution.</p><pre>// component.js<br>import withStyles from &#39;react-jss&#39;;</pre><pre>const styles = (theme) =&gt; ({<br>  wrapper: {<br>    fontSize: &#39;1.4em&#39;,<br>    color: theme.primaryColor,<br>    height: (props) =&gt; props.size<br>  }<br>});</pre><pre>const Component = ({ classes }) =&gt; {<br>  return (<br>    &lt;div className={classes.wrapper}&gt;<br>      My fancy component<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default withStyles(styles)(Component);</pre><pre>// app.js<br>import { ThemeProvider } from &#39;react-jss&#39;;</pre><pre>const theme = {<br>  primaryColor: &#39;#51abff&#39;<br>};</pre><pre>// rendering<br>&lt;ThemeProvider theme={theme}&gt;<br>  &lt;Component size=&quot;32px&quot; /&gt;<br>&lt;/ThemeProvider&gt;</pre><p>The theme object is available when instead of styles object, you create a function that returns the styles object. Component’s props are available in a slightly more annoying way, as a argument for function returning value of each property.</p><h4>Reusing and overriding styles</h4><p>When it comes to extending styles, well, JSS does not provide any simple way of doing so. But, then again, they are all JS object, so we can export styles and extend them on our own using the spread operator.</p><pre>// component.js<br>export const styles = {<br>  wrapper: { <br>    // original styles<br>  }<br>};</pre><pre>const Component = () =&gt; {<br> // Component&#39;s logic<br>};</pre><pre>export default withStyles(styles)(Component);</pre><pre>// fancy-component.js<br>import { styles as defaultStyles } from &#39;./component&#39;;</pre><pre>export const styles = {<br>  wrapper: {<br>    ...defaultStyles.wrapper,<br>    color: &#39;red&#39;<br>  }<br>}</pre><p>A bit of work, but it’s very explicit. No under-the-hood magic. There is a <a href="http://cssinjs.org/jss-extend">extend-plugin</a>, however its usage is very similar to the spread operator.</p><p>JSS has a neat feature that is not available in other libraries, and that’s ability to override default styles of the component. You can call the withStyles HoC again and again on component, overriding it’s default styles, like so:</p><pre>// componentA.js<br>const styles = {<br>  wrapper: {<br>    color: &#39;red&#39;,<br>    fontSize: &#39;1.4em&#39;<br>  }<br>  paragraph: {<br>    fontSize: &#39;1.2em&#39;,<br>    color: &#39;gray&#39;<br>  }<br>};</pre><pre>const ComponentA = () =&gt; {<br>  // ...<br>};</pre><pre>export default withStyles(styles)(ComponentA);</pre><pre>// componentB.js<br>const stylesA = {<br>  wrapper: {<br>    color: &#39;blue&#39;<br>  }<br>};</pre><pre>const StyledA = withStyles(stylesA)(ComponentA);</pre><pre>const ComponentB = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;StyledA /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Because withStyles performs a shallow merge of the style objects, the StyledA component will contain the original styles for paragraph, but it will have only the newest styles for wrapper. This means that it will have only the color: blue property but it will lose the fontSize: 1.4em property.</p><p>You can obviously combine the two methods to override styles with extending the existing ones. However, since it is a HoC, you can write your own HoC that does just that.</p><h4>Other features</h4><p>JSS comes with variety of <a href="http://cssinjs.org/plugins">plugins</a>. You can use them, for example, to write styles inside template literals, if that’s your thing, or to extend existing classes via class names or objects.</p><h4>Debugging</h4><p>When it comes to debugging, JSS is very user friendly. At the very beginning, it renders human-friendly class names, so you can quickly find your way around the generated HTML markup. It also does not change the generated components’ names, as it only works on the className property, which is quite nice.</p><p>Pros:</p><ul><li>Local Scope</li><li>Theming, dynamic styles</li><li>No artificial code splitting</li><li>Overriding default styles (!)</li><li>works as a HoC</li></ul><p>Cons</p><ul><li>No native style extending solution (but you can work around this)</li></ul><h3>Conclusion</h3><p>It’s time to sum up. Is there a clear winner? In my opinion, yes. JSS takes the top spot. It gives me all of the features of other CSS-in-JS solutions and doesn’t forces me to create super-small components each time I need styling for a div. In addition to that, it works as a HoC, so if I don’t like the default behavior (like when overriding styles) I can always create my own HoC that wraps it and changes the behavior. It’s simple to use and flexible. And at the end of the day, it’s the solution that devs from the <a href="http://www.material-ui.com/#/">Material UI</a> are <a href="https://material-ui-next.com/customization/css-in-js">gonna use</a>. For me, that’s a hell of a recommendation for JSS.</p><blockquote>As I already mentioned, I thought that SASS + CSS Modules were the future. But now I can clearly see, that CSS in JS is at least as good, with JSS being my favorite. It’s really usable and works great in the real-life development. My personal pick after doing the research: JSS.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ZPFacWtEYCiFBgae_-iBJg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0b50bbbd740" width="1" height="1" alt=""><hr><p><a href="https://medium.com/warsawjs/css-in-js-in-real-life-e0b50bbbd740">CSS in JS in real-life</a> was originally published in <a href="https://medium.com/warsawjs">WarsawJS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>