# OurJS — Nayan Kumar: full text reference > Content from https://ourjs.in. Personal portfolio, browser tools and engineering journal. ## Profile Nayan Kumar (He/Him) — Engineering Team Lead. New Delhi, Delhi, India. I lead engineering teams and build scalable, high-performance web applications. My work brings together React, Angular, clean architecture, CI/CD, and a focus on reliable user experiences. Skills: React.js, Angular, AngularJS, JavaScript, HTML5, CSS3, Bootstrap, jQuery, Wireframing, UI/UX design, Adobe Photoshop, CI/CD, AWS, .NET Framework, SQL, Product strategy, Engineering leadership, Team mentoring. Email: 1019nayank@gmail.com. Phone: +91 8581939496. LinkedIn: https://www.linkedin.com/in/nayan-kumar-web-developer/ Résumé: https://ourjs.in/nayan-kumar-resume.pdf ## Experience - Engineering Team Lead, Rentalgini. Jan 2026 – Present. Noida, Uttar Pradesh · On-site. Engineering leadership across frontend, backend, mobile, and DevOps, working with cross-functional teams to deliver scalable products. - Lead Software Development Engineer, Rentilium. Mar 2025 – Present. Hybrid. Leading software development for SaaS and enterprise applications with attention to architecture, performance, and maintainability. - Senior Software Engineer, Rentilium. Feb 2025 – Mar 2025. India. - Frontend Developer, Rentilium. May 2024 – Feb 2025. India · On-site. React.js and frontend development. - Frontend Web Developer, Rentilium. May 2024 – Sep 2024. Sector 137, Noida · On-site. React and HTML5 frontend development. - Lead UI/UX Developer, Genient Technologies. Sep 2023 – Apr 2024. Noida, Uttar Pradesh · On-site. UI/UX development with AngularJS and React. - Software Engineer · Front-End Developer, Chetu, Inc.. Feb 2023 – Aug 2023. Noida, Uttar Pradesh · On-site. Frontend development, HTML5, and wireframing. - UI/UX Developer, Alexion Techno Pvt. Ltd. Jun 2021 – Jan 2023. Noida, Uttar Pradesh · On-site. UI/UX development, wireframing, and Adobe Photoshop. - Web Developer · Internship, Alexion Techno Pvt. Ltd. Jan 2021 – May 2021. . Web development with HTML5 and Adobe Photoshop. ## Education and certification - MAAC, Delhi: APDMD · Graphic & Web Design. Mar 2019 – Nov 2021. Graphic and web design, including jQuery and CSS. - Jawahar Navodaya Vidyalaya (JNV): Matriculation. . - Product Management: Building a Product Strategy, LinkedIn, May 2026. ## Project contributions Professional projects are team contributions. OurJS is Nayan’s personal project. - Rentilium — SaaS ERP: Frontend and engineering contribution to a SaaS ERP platform, progressing from frontend development to engineering leadership. A team product. My roles progressed from frontend development to Lead Software Development Engineer. Stack: React.js · HTML5 · CSS3 · JavaScript. - Happy Living — Website: A collaborative website project associated with Rentilium, bringing together CSS3, JavaScript and frontend development. A collaborative project associated with my work at Rentilium. Stack: CSS3 · JavaScript · Frontend development. - Alex School ERP: A SaaS school ERP project, with .NET Framework and SQL among my associated project skills. A professional project contribution. The artwork illustrates the engineering context. Stack: .NET Framework · SQL · SaaS. - OurJS — My Developer Toolkit: My portfolio, free browser utilities and technical journal, combining practical frontend engineering with accessible interactions. Explore the working tools on this site. Supported processing runs locally in the browser. Stack: Next.js · TypeScript · Browser APIs. ## Browser tools Free browser utilities. Tool inputs and selected images are processed on the device. URLs entered into tools are not fetched. - [Image Compressor](https://ourjs.in/tools/image-compressor/): Compress JPG, PNG and WebP images in your browser. - [Image Resizer](https://ourjs.in/tools/image-resizer/): Resize images to custom dimensions without uploading. - [Image Converter](https://ourjs.in/tools/image-converter/): Convert images to JPG, PNG or WebP. - [JSON Formatter](https://ourjs.in/tools/json-formatter/): Format, validate and minify JSON. - [Base64 Encoder / Decoder](https://ourjs.in/tools/base64/): Encode or decode Unicode text safely. - [Word Counter](https://ourjs.in/tools/word-counter/): Count words, characters, sentences and reading time. - [QR Code Generator](https://ourjs.in/tools/qr-generator/): Generate downloadable QR codes from text or URLs. - [Password Generator](https://ourjs.in/tools/password-generator/): Generate strong random passwords using browser cryptography. - [Color Converter](https://ourjs.in/tools/color-converter/): Convert HEX colors into RGB and HSL values. - [SEO Meta Preview](https://ourjs.in/tools/meta-preview/): Preview your Google-style title and description snippet. - [URL Encoder / Decoder](https://ourjs.in/tools/url-encoder/): Encode URL components or decode percent-encoded text. - [Query String Parser](https://ourjs.in/tools/query-string-parser/): Inspect URL query parameters, including repeated keys. - [UUID Generator](https://ourjs.in/tools/uuid-generator/): Generate random version 4 UUIDs with browser cryptography. - [Timestamp Converter](https://ourjs.in/tools/timestamp-converter/): Convert Unix seconds, milliseconds and ISO dates to UTC. - [CSV to JSON](https://ourjs.in/tools/csv-to-json/): Turn CSV rows into JSON, including quoted and multiline fields. - [JSON to CSV](https://ourjs.in/tools/json-to-csv/): Convert an array of JSON records into downloadable CSV. - [HTML Entity Encoder](https://ourjs.in/tools/html-entities/): Encode HTML special characters or decode character references. - [Regular Expression Tester](https://ourjs.in/tools/regex-tester/): Test JavaScript patterns in a worker with an execution timeout. - [Text Difference Checker](https://ourjs.in/tools/text-diff/): Compare two texts and inspect line additions and removals. - [Text Case Converter](https://ourjs.in/tools/case-converter/): Convert text to upper, lower, title, sentence or camel case. - [Text Cleaner](https://ourjs.in/tools/text-cleaner/): Trim lines, normalize spaces and remove empty lines. - [Duplicate Line Remover](https://ourjs.in/tools/duplicate-line-remover/): Remove repeated lines while keeping their original order. - [Line Sorter](https://ourjs.in/tools/sort-lines/): Sort lines alphabetically, in reverse or with natural numbers. - [Reading Time Calculator](https://ourjs.in/tools/reading-time-calculator/): Estimate reading time using an adjustable words-per-minute rate. - [URL Slug Generator](https://ourjs.in/tools/slug-generator/): Make a readable lowercase URL slug from a title. - [Keyword Occurrence Counter](https://ourjs.in/tools/keyword-density/): Count exact word and phrase occurrences in a text draft. - [Meta Tag Generator](https://ourjs.in/tools/meta-tag-generator/): Create escaped title, description, canonical and social HTML tags. - [Robots.txt Generator](https://ourjs.in/tools/robots-generator/): Draft crawler directives and a sitemap URL for your website. - [XML Sitemap Generator](https://ourjs.in/tools/sitemap-generator/): Build sitemap XML from a list of public canonical URLs. - [UTM Campaign URL Builder](https://ourjs.in/tools/utm-builder/): Add campaign source, medium and campaign parameters to a URL. - [Color Contrast Checker](https://ourjs.in/tools/contrast-checker/): Measure an opaque sRGB color pair against WCAG contrast ratios. - [CSS Gradient Generator](https://ourjs.in/tools/gradient-generator/): Preview a two-color linear gradient and copy its CSS. - [Box Shadow Generator](https://ourjs.in/tools/box-shadow-generator/): Adjust offsets, blur and spread, then copy the CSS shadow. - [Border Radius Generator](https://ourjs.in/tools/border-radius-generator/): Design individual rounded corners with a live preview. - [Aspect Ratio Calculator](https://ourjs.in/tools/aspect-ratio-calculator/): Simplify dimensions to a ratio and calculate a proportional size. - [SHA-256 Hash Generator](https://ourjs.in/tools/sha256-generator/): Calculate a SHA-256 digest of UTF-8 text on your device. ## Engineering journal ### A Frontend Release Checklist That Checks the Actual User Journey Canonical URL: https://ourjs.in/blog/frontend-release-checklist/ Author: Nayan Kumar. Published: 2026-10-26. Category: DevOps. Review content, navigation, responsiveness, metadata and the deployed artifact without confusing a green build with a finished release. #### Define the release you intend to ship Record the source revision, artifact identifier and scope of the change. A release checklist needs a concrete target; otherwise, one person may review a preview while another uploads files from a later build. Note which routes and user tasks changed so verification can focus on real consequences rather than repeating an unrelated list from a previous project. #### Check content and primary actions Read the visible copy for accuracy and complete the main task. For a portfolio, open a project, use the contact path and download the résumé. For a utility, test a valid input and a useful error state. A button that looks clickable but has no working destination is a product failure even if every stylesheet compiled correctly. #### Exercise navigation and layout Open deep URLs directly, follow the breadcrumb and test the mobile menu with a keyboard. Inspect a narrow viewport for overflow, clipped labels and controls hidden by fixed elements. Check meaningful focus indicators and reduced-motion behavior. These tests should reflect the actual components being released rather than treating the homepage as a substitute for every interior layout. #### Review one representative content addition Suppose the release adds a new CSV-to-JSON tool. Confirm its directory card, detail page, instructions, example, download behavior and sitemap entry. Submit malformed CSV and verify the feedback. This small end-to-end slice catches several integration errors that isolated checks miss, including a correct tool implementation connected to the wrong route or an explanation of unsupported features. #### Inspect technical delivery Review document status codes, titles, canonical URLs, sharing images and expected indexing directives. Check that fonts, scripts and images load without missing-file responses. Confirm cache behavior for HTML and versioned assets, and retain the previous release. Avoid publishing credentials or private environment values while adding diagnostic output to investigate a last-minute build problem. #### Repeat the critical checks after publication Use the final public hostname and record the observed result of a few high-value checks. Include a deep route and one primary task, because upload success does not prove correct hosting configuration. If something fails, identify whether the issue belongs to the artifact, configuration or delivery layer. Mark the release verified only when the intended version and behavior are actually visible. Sources: - [Next.js: static export deployment considerations](https://nextjs.org/docs/app/guides/static-exports): Reference source. - [Google: developer SEO guidance](https://developers.google.com/search/docs/fundamentals/get-started-developers): Reference source. ### A Technical SEO Page Audit You Can Repeat Before Every Release Canonical URL: https://ourjs.in/blog/technical-seo-page-audit/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Inspect the response, visible content, metadata, links and indexing signals with a small, repeatable page-level audit. #### Start with the actual response Open the final public URL in a fresh browser session and inspect the document request. Record its status, redirects and response headers before examining the design. A beautiful page returned as an error, an accidental redirect chain, or a login screen is an access problem first. Keep the exact tested URL with your notes. #### Compare HTML with the rendered page Read the response HTML and then inspect the rendered DOM. The page title, main heading and useful explanatory content should be available to the intended audience without waiting for a private API or interacting with a control. JavaScript can enhance the page, but check what happens when a script fails or a request times out. #### Trace a practical example For a hypothetical image-resizer page, verify that its title describes resizing, its main heading names the tool, and its instructions explain width, height and output format. Follow its link from the tools directory, process a small sample image, and return through the breadcrumb. This tests both discoverability and the promise made to the visitor. #### Check the signals together Inspect the canonical URL, robots directives and sitemap entry as one group. They should describe the same intended public page. Review social metadata separately because a correct sharing card does not prove correct indexing. Validate structured data against visible facts rather than assuming that syntactically valid JSON describes the page accurately. #### Prioritize findings by consequence Fix blocked access, incorrect status codes and missing content before polishing a description. Then address conflicting canonical signals, broken navigation and unclear headings. Keep cosmetic preferences separate from evidence-backed faults. A duplicated title across unrelated pages needs a specific correction; a dislike of a headline is an editorial discussion, not automatically a technical defect. #### Make the audit reproducible Store a short checklist beside the release process: URL, expected status, title, canonical, indexability, one working inbound link and one successful user task. Repeat it against the deployed artifact, not just the development server. Search Console can add indexing evidence later, while local checks establish only what your own tests actually observed. Sources: - [Google: SEO guidance for developers](https://developers.google.com/search/docs/fundamentals/get-started-developers): Reference source. ### Accessible Dialog Focus: Open, Close and Return Predictably Canonical URL: https://ourjs.in/blog/accessible-dialog-focus/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Plan focus behavior for modal dialogs using native HTML capabilities and a clear dismissal path. #### Decide whether a dialog is necessary A modal interrupts the current task and makes the surrounding page unavailable. That can be appropriate for a focused confirmation or preview, but a project description or ordinary navigation often works better directly on the page. Reducing unnecessary dialogs also reduces the amount of focus management the application has to get right. #### Start with the native element A dialog opened with showModal() has modal behavior that a styled div does not gain automatically. Give it a clear accessible name through a visible heading referenced by aria-labelledby. Use ordinary form controls and buttons inside it. Opening a dialog by changing CSS alone is different from invoking the browser’s modal dialog behavior. #### Choose an intentional first focus target The first focused item should fit the task. For a brief confirmation, a safe action may be appropriate. For longer explanatory content, focusing a meaningful introductory element can help people read before choosing. Do not add focusable wrappers everywhere; decide what the reader needs to understand when the modal first appears. #### Provide more than a backdrop gesture Include a visible close or cancel button with a meaningful accessible name. Test the supported keyboard dismissal behavior, including Escape, and consider whether any confirmation must happen before closing. Clicking outside may be a useful convenience for some dialogs, but it cannot be the only dismissal method a person is expected to discover. #### Return to the original context Remember the control that opened the dialog and verify that focus returns there when it closes. If that control no longer exists, select a sensible next location in the same workflow. A closing animation should not leave focus stranded in hidden content or move it to the start of the document without explanation. #### Exercise the full lifecycle Open the dialog with a keyboard, move through its controls, dismiss it, and continue the original task. Repeat after route changes and after removing a list item that opened the dialog. Confirm that the background is not reachable while modal and that repeated opening does not attach duplicate event listeners or create multiple overlapping instances. Sources: - [MDN: the dialog element](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/dialog): Reference source. ### Accessible Form Labels: Clear Names for Every Field Canonical URL: https://ourjs.in/blog/accessible-form-labels/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Connect visible labels to inputs, preserve useful hints, and avoid forms that depend on placeholders. #### Keep the label after typing A placeholder can suggest an example, but it disappears as soon as someone starts entering a value. The field still needs a persistent label. On a contact form, Your name and Email address should remain visible while the person reviews the message, corrects a typo or returns to an unfinished draft. #### Associate text with the control Use a label whose for value matches the input’s unique id, or wrap the control in its label. Both approaches create a meaningful relationship. Clicking the label should focus the intended field. This larger activation area is useful for small checkboxes as well as ordinary text inputs on a touch screen. #### Separate names from help text A label identifies a field; a hint explains its expected format. For a project budget field, the label might be Estimated budget, with a separate note that the value is optional and should be entered in a particular currency. Associate that note using aria-describedby so the accessible name stays concise and the additional instruction remains available. #### Use the right input purpose Type and autocomplete attributes can support the task. An email field can use type="email" and autocomplete="email"; a name field can use autocomplete="name". These do not replace a visible label. They help the browser offer an appropriate keyboard or saved value while the label tells the person what the site is asking for. #### Name groups as well as fields Related radio buttons need a shared question, not just individual labels. A fieldset with a legend such as Preferred contact method connects choices like Email and Phone. Avoid placing unrelated fields into one enormous group. The relationship should explain the choice someone is making, especially when the options are read independently of their visual layout. #### Inspect names in real states Check the accessibility tree before typing, after autofill and when validation fails. Confirm that every field has a sensible name and duplicate ids are absent. Turn off placeholder styling temporarily to expose missing labels. Finally, check that long labels wrap without colliding with controls, hints, character counters or inline error messages. Sources: - [MDN: the label element](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/label): Reference source. ### Accessible SVG Icons: Decorative Shapes and Meaningful Controls Canonical URL: https://ourjs.in/blog/accessible-svg-icons/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Give icon-only actions a clear name and prevent decorative SVGs from adding repetitive screen reader output. #### Classify the icon’s job An arrow beside Read project repeats a meaning already provided by the text. A standalone magnifying-glass button, however, may be the only visible clue that it opens search. These cases need different treatment. Decide whether the icon communicates information, supports a text label, or acts as the visual representation of a control. #### Name the control instead of the drawing For an icon-only button, a clear aria-label such as Open navigation can name the button while the SVG itself is hidden from assistive technology. The visible control still needs a reasonable target size and focus state. A tooltip may help sighted readers, but it should not be the only source of the accessible name. #### Keep decorative SVGs quiet An SVG that merely decorates a text link can use aria-hidden="true" so it does not add an extra announcement. Avoid placing important text inside that hidden subtree. Review the final link name: it should read naturally once, rather than saying the title, arrow icon, right arrow and a repeated tooltip label. #### Describe informative standalone graphics When an SVG is itself an informative graphic, provide an accessible name, often through a title element referenced by aria-labelledby. More complex graphics may also need a description or nearby explanation. Use unique ids for repeated inline graphics; duplicated title ids can associate a graphic with the wrong instance when several cards appear together. #### Preserve the visual language Use currentColor when an icon should follow its surrounding text color, and verify its contrast against each theme surface. Thin strokes can disappear at small sizes even when the color pair looks promising. Icons must not be the sole indicator of an error, a required field or an important state change. #### Check output and interaction together Inspect the accessibility tree for a text button, an icon-only toggle and a standalone chart. Navigate with a keyboard and confirm the action is understandable before activation. Resize the icons and test a forced-colors environment where available. A compact SVG file is only one part of a usable icon system. Sources: - [MDN: SVG title element](https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Element/title): Reference source. ### Add a Skip Link That Actually Reaches the Main Content Canonical URL: https://ourjs.in/blog/skip-link-implementation/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Let keyboard users bypass repeated navigation with a visible, reliable link to the page’s main content. #### Identify the repeated obstacle A site header may contain a logo, six navigation links, a theme control and a contact button. Repeating all those stops on every page makes a simple reading task unnecessarily slow. A skip link offers a direct route to the main content while leaving the regular navigation available when someone actually needs it. #### Use a real fragment link Place a link near the beginning of the body and point it to the main region’s unique id. For example, an href of #main-content should resolve to a main element with that exact id. This works with ordinary browser navigation and does not require a click handler or an animation library to decide where the reader goes. #### Make the destination useful Moving the viewport is only part of the interaction. The keyboard journey should continue from the content after activation. A main element with tabindex="-1" can be a programmatic focus destination without adding an extra regular Tab stop. Verify behavior in the browsers and assistive technology combinations you support rather than assuming the fragment alone handles everything. #### Keep the link visible when focused An always-visible skip link is straightforward. If the design initially places it offscreen, reveal it when focused and position it above sticky navigation. Use a strong foreground and background combination. Do not hide it with display:none, because that removes it from keyboard access instead of providing a shortcut that can be discovered. #### Account for sticky headers A fixed header can cover the destination’s first heading. Add an appropriate scroll offset through scroll-margin or the scrolling container’s scroll-padding. Test with the expanded header height on smaller screens. The skip action should expose the content title, not land halfway through a paragraph or underneath a floating navigation panel. #### Verify the first interaction Reload the page, press Tab once, and confirm the skip link is visible. Activate it, then press Tab again and inspect where focus moves. Repeat on an article, a tool and the contact page. Also check that the id is unique: duplicate fragment targets can make the shortcut depend on incidental markup order. Sources: - [W3C: adding a skip link](https://www.w3.org/WAI/WCAG21/Techniques/general/G1): Reference source. ### Add Parallax Depth Without Taking Over the Reader’s Scroll Canonical URL: https://ourjs.in/blog/parallax-without-scroll-hijacking/ Author: Nayan Kumar. Published: 2026-10-26. Category: Animation. Keep ordinary scrolling intact while giving decorative layers a restrained sense of depth. #### Keep the browser in charge Parallax works by moving decorative layers at different apparent speeds. It does not require replacing native scrolling with a simulated camera. Preserve the browser’s wheel, touch, keyboard and anchor behavior. A reader should be able to reach a heading, use Page Down or return through browser history without negotiating a custom scroll controller. #### Choose a few nonessential layers A portfolio hero might have a browser mockup, a small floating label and an orbital background. Let those layers move slightly while the headline and primary action remain stable. Avoid shifting a paragraph while someone reads it. The content hierarchy should work exactly the same way when all depth movement is turned off. #### Bound the movement Use a small maximum displacement rather than allowing an element to travel indefinitely with scroll distance. For example, map a layer’s position around the viewport center to an offset clamped between minus 24 and plus 24 pixels. This keeps it inside the intended composition and reduces collisions with surrounding sections at unusual viewport sizes. #### Batch the frame work A scroll listener should collect only the work needed for the visible scene. Group geometry reads before style writes and update transforms rather than repeatedly changing layout dimensions. RequestAnimationFrame can help organize one pending update, but it does not automatically reduce a scroll stream’s frequency. Keep the callback small and measure the complete effect. #### Treat touch and motion preferences carefully A complex depth effect may add little value on a small phone. Use a simpler static composition there if it improves reading and battery use. Honor reduced-motion preferences and any explicit motion switch. When motion is disabled, reset offsets to the final design positions instead of freezing the scene in an awkward partially translated state. #### Verify navigation as well as appearance Test a long scroll, an anchor jump, resizing the window and browser back navigation. Inspect whether a floating layer covers a button or leaks beyond the page width. Check performance with the scene visible and offscreen. A successful parallax treatment adds a little dimensionality while leaving the reader’s route through the page completely unsurprising. Sources: - [MDN: document scroll event](https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event): Reference source. ### Angular Signals: Keep Source State and Derived Values Separate Canonical URL: https://ourjs.in/blog/angular-signals-basics/ Author: Nayan Kumar. Published: 2026-10-26. Category: Angular. Use writable signals and computed values to express small, understandable reactive relationships. #### Begin with a value someone can change A writable signal represents a value that the feature owns and can update. Think of a selected category or search query in a portfolio directory. Reading the signal through its getter participates in Angular’s reactive tracking. Start with this small relationship before attempting a global state architecture; the useful question is which part of the feature owns each decision. #### Derive the visible collection Suppose projects is a source collection and query is a writable signal. A computed value can filter the projects using the current query, and another display can read the resulting count. The count does not need independent writable state. Keeping derived information computed avoids synchronization code whose only job is copying one reactive value into another after each edit. #### Update values through a clear operation Use set when assigning a replacement value and update when calculating a new value from the previous one. For an object or array, prefer a deliberate replacement for a changed branch rather than hidden deep mutation. Exposing a readonly signal prevents consumers from calling its writable methods, but it does not automatically make a nested object deeply immutable. Data ownership still needs a contract. #### Understand dependency changes Computed relationships track the signals read during a derivation. A branch that does not read a particular signal may not depend on it for that evaluation. This can be useful, but it should remain understandable from the function. Avoid side effects inside a computed value; a derivation should describe a result, not start a request or change another piece of source state unexpectedly. #### Reserve effects for external coordination A browser storage write, logging integration or nonreactive widget may need synchronization outside the calculated view. That is a different responsibility from computing a filtered array. Avoid chains of effects that shuttle values around because they make the direction of change harder to follow. Keep the source-to-derived relationship explicit, and use the framework’s current lifecycle guidance for resource cleanup. #### Verify the dependency story Change the query, replace the collection and toggle branches that enable or disable a derived view. Confirm that the displayed count and rows agree. Test object updates without relying on incidental unrelated renders. Review which values are writable and why. A small reactive model is successful when another developer can trace an edit to its visible consequences without searching for hidden synchronization loops. Sources: - [Angular: signals overview](https://angular.dev/guide/signals): Reference source. ### Article Structured Data Should Describe What Readers Can Verify Canonical URL: https://ourjs.in/blog/article-structured-data/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Connect article titles, authors, publication dates and images to visible editorial facts instead of filling fields with guesses. #### Model the editorial facts first Before writing JSON-LD, decide who wrote the article, when it was published, what its headline is and which image represents it. Put those facts in the content record used by the visible page. Structured data becomes easier to maintain when it is an output of that record rather than a second, manually edited version of the article. #### Use an appropriate article type A technical journal entry can be represented with BlogPosting, a subtype of Article. Include supported properties that accurately describe the page, such as headline, author, datePublished, dateModified and image. Do not choose a type simply because it appears to offer more prominent search presentation. The content and the markup need to tell the same story. #### Work through a publication example Suppose a guide is first published on 26 October and substantially revised later to add tested deployment steps. Preserve the original publication date and record the later modification date. If a rebuild changes only a stylesheet, leave the article’s editorial dates alone. This distinction helps readers understand the age of the advice and why it was updated. #### Make identity links meaningful Link the author to a real profile page that explains the person’s relevant background, and identify the publisher consistently. A personal portfolio should not invent an editorial team or organization to make the site sound larger. When the author is known, use that verified identity; when information is missing, do not fabricate credentials to complete a field. #### Keep images and content accessible The representative image should resolve at its public URL and make sense for the article. Avoid pointing every article to a nonexistent route or a private asset. Escape serialized JSON safely when inserting it into HTML. Readers should still be able to understand the article when the structured-data script is removed because the script is descriptive metadata, not the content itself. #### Check syntax and correspondence Parse generated JSON-LD during the build, then compare headline, dates and byline with the visible page. Test representative URLs in a structured-data validation tool after deployment. Fix both syntax errors and factual mismatches. Correct markup can support understanding and eligibility, but it does not guarantee a rich result or compensate for an article that fails to answer its stated question. Sources: - [Google: article structured data](https://developers.google.com/search/docs/appearance/structured-data/article): Reference source. ### Build a Simple FAQ Accordion with Details and Summary Canonical URL: https://ourjs.in/blog/details-summary-accordion/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Use native disclosure elements for compact supporting content without hiding the page’s main answer. #### Choose supporting content An FAQ disclosure is useful when readers have different follow-up questions. It is less useful when the collapsed panel contains the only explanation of what the page does. Keep essential instructions and the main answer visible. Reserve accordions for details that people can choose to explore after they understand the primary content. #### Use the native disclosure pair Place a summary as the label of a details element, followed by the panel content. The browser handles the basic open and closed interaction. Write the summary as a complete question, such as Are uploaded images sent to a server? A vague label like More does not help someone decide whether the panel is relevant. #### Preserve an obvious interactive cue The default marker communicates that the row expands. A custom plus or chevron can replace it visually, but the result still needs a visible focus treatment and enough space for touch interaction. Keep decorative icons out of the accessible name. Let the actual question provide the control’s meaningful label. #### Let answers remain real content Put answer text, lists and ordinary links inside the panel rather than rendering them only after the first click. For example, an image-tool FAQ can explain output format limitations and link to the converter. Native collapsed content remains part of the document; the disclosure state should not become an excuse for loading important explanations unreliably. #### Be careful with exclusive behavior Allowing several panels to stay open can help people compare answers. If the design requires an exclusive group, verify its browser support and keyboard behavior in the environments you target. Avoid unnecessarily reimplementing every toggle with JavaScript merely to force one panel closed; that can add complexity without improving the reader’s task. #### Test more than the first click Open a question with the keyboard, follow a link inside the answer, then return and close the disclosure. Try a long question at a narrow width and make sure its marker does not overlap text. Check print output as well: answers that disappear from the printed page may need a dedicated print treatment. Sources: - [MDN: the details element](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/details): Reference source. ### Build Accessible React Components from Native HTML Canonical URL: https://ourjs.in/blog/react-accessible-components/ Author: Nayan Kumar. Published: 2026-10-26. Category: React. Preserve labels, keyboard behavior and predictable IDs as interfaces become reusable components. #### Start with the interaction’s native element React changes how an interface is composed, but the browser still receives HTML controls and links. A button should perform an action, a link should navigate, and a labeled input should collect a value. Choosing the correct native element preserves useful keyboard and accessibility behavior. Recreating that behavior on a generic container adds responsibilities that the original control already handles. #### Follow a reusable field example Imagine a ProjectNameField component containing a visible label, an input, a short hint and an optional error. Each instance needs a unique association between those elements. Generate a stable ID for the component instance when needed, and connect the label and descriptions to the input. Two fields on the same page should not accidentally share one hardcoded identifier. #### Keep the visible name useful A placeholder disappears during entry and should not be the only explanation of a field. A clear visible label also helps someone using voice input or revisiting a partially completed form. If an icon-only button needs an accessible name, describe the action rather than the picture: Download résumé communicates intent more clearly than Down arrow. Keep visible and programmatic naming compatible. #### Model changing states accurately A disclosure needs to expose whether its content is expanded. A disabled action should reflect whether it can actually be used. Error and status feedback should be associated with the right control or announced appropriately without repeating on every keystroke. Adding ARIA attributes does not replace the underlying state logic; the attributes must stay synchronized with the same state that controls the visible interface. #### Design focus as part of the feature Opening a dialog, closing a menu or deleting a focused row can change where keyboard interaction should continue. Plan those transitions instead of relying on whichever element happens to remain in the DOM. Keep a visible focus indicator and avoid animated transforms that make a control difficult to locate. Respect reduced-motion preferences where decorative motion is involved. #### Verify beyond the component screenshot Use Tab, Shift+Tab, Enter, Space and Escape where relevant to the control pattern. Render multiple instances and inspect their labels and IDs. Check long error text, high zoom and a screen-reader workflow when possible. A reusable component improves accessibility only if it consistently preserves semantics and behavior across its real usages, rather than looking correct in one isolated example. Sources: - [React: useId for accessible associations](https://react.dev/reference/react/useId): Reference source. - [W3C WAI: labeling controls](https://www.w3.org/WAI/tutorials/forms/labels/): Reference source. ### Build an Accessible Heading Structure Before Styling Your Page Canonical URL: https://ourjs.in/blog/accessible-heading-structure/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Plan headings as a readable outline, then style their appearance independently from their document level. #### Write an outline first A heading explains what the next block of content is about. On a portfolio project, the page title could identify the project, followed by sections covering the problem, approach, implementation and outcome. Writing that outline before designing cards makes it easier to notice missing explanations and sections that repeat the same idea. #### Separate hierarchy from size Choose the heading level from the document relationship, not the font size you want. A small card title can be an h3, while an introductory h2 can be visually enormous. Classes control appearance. This separation lets you change the design without silently changing the information structure a reader encounters through heading navigation. #### Use one clear page title A practical default is one h1 that describes the current page. Beneath it, use h2 for major sections and h3 for subsections. For example, an h2 named Implementation could contain h3 headings for Data flow and Accessibility. The nesting should explain how the ideas relate rather than imitate a collection of typographic styles. #### Make headings useful out of context Compare Learn more with Image compression tradeoffs. The second heading tells someone what the section contains even when heard in a list of headings. Avoid stuffing headings with variations of a keyword. Readers need accurate labels that distinguish sections, especially when a long article contains several closely related implementation details. #### Handle reusable cards carefully A component cannot always assume that its title should be h2. The same project card might appear under an h2 on the homepage and directly beneath the page title on a directory. Pass an appropriate heading element into the component, or create a clear rule for the contexts in which it is used. #### Review the outline as a reader List the headings without their paragraphs and ask whether they tell a coherent story. Check for empty headings, skipped levels caused by visual styling and decorative text incorrectly marked as a heading. Test a long translated title and larger text settings as well: semantic correctness does not excuse clipping or a layout that conceals the title. Sources: - [MDN: HTML heading elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/Heading_Elements): Reference source. ### Build and Read Query Strings with URLSearchParams Canonical URL: https://ourjs.in/blog/url-search-params/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Handle repeated parameters, encoding and filter state with an explicit query-string contract. #### Treat a query string as structured input A filter URL is more than a string appended after a question mark. It contains keys, values, possible duplicates and encoding rules. Using URL and URLSearchParams makes those parts explicit. Start with an agreed contract for names and defaults so that browser state, shared links and server interpretation describe the same filtering operation. #### Build a concrete filter link Suppose a journal supports category=React and search=state updates. Create a URL from a known base, then set those search parameters. The browser handles encoding of the space and other reserved characters. Avoid manually concatenating an unescaped search term, which can accidentally introduce a new parameter if the visitor types an ampersand or equals sign. #### Decide whether a key can repeat A single category can use set, while multiple selected tags may need append and getAll. Calling get returns one value, not the entire repeated collection. For an example with tag=css and tag=accessibility, decide whether the server expects two keys, one comma-separated value or another format. None of those contracts can be inferred from the visual checkbox list alone. #### Validate values after decoding URLSearchParams handles representation, not application rules. A page parameter still needs to be a positive integer within the supported range. A sort value should come from an allowed set. Do not use a query value directly as an unrestricted redirect destination or HTML fragment. Keep invalid and unsupported input behavior deliberate and consistent. #### Make navigation state predictable When changing a filter, preserve unrelated parameters only if the feature requires them. Reset page numbers when a new query changes the result set. Choose pushState for meaningful history steps and replacement for edits that should not create dozens of Back-button stops. Shareable state should also be reflected in the controls when a saved link is opened. #### Check encoded and repeated cases Try values containing plus signs, spaces, ampersands, Unicode and percent symbols. Verify repeated keys, an empty value and a missing key independently. Copy the finished URL into a new tab and confirm that it reconstructs the same screen. A query-string helper is successful when links behave consistently across reload, sharing and browser navigation. Sources: - [MDN: URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams): Reference source. ### Build Breadcrumbs That Help Visitors Before Adding JSON-LD Canonical URL: https://ourjs.in/blog/breadcrumb-structured-data/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Keep visible hierarchy, linked destinations and BreadcrumbList data in agreement across a growing site. #### Choose a useful hierarchy A breadcrumb should explain where a page belongs in the site’s organization. Home, Journal, and a named article is usually more helpful than exposing internal component directories. Start with the visitor’s mental model. The path does not need to reproduce every part of a storage location, especially when a content system has implementation-specific folders. #### Make the visible trail work Render the trail as navigation with an accessible label. Ancestor items should be ordinary links, and the current location should be clearly identified. Keep separators visually distinct without turning them into misleading destinations. On narrow screens, allow the trail to wrap so a long article title does not force the entire page to overflow horizontally. #### Describe the same trail in data BreadcrumbList JSON-LD represents a sequence of ListItem entries with positions, names and URLs as appropriate. Generate the visible trail and structured data from one array so they cannot quietly diverge. Use the site’s canonical public addresses rather than relative build paths or preview hostnames that only work on a developer’s machine. #### Try a concrete tool hierarchy For a color converter, a practical trail is Home → Free Tools → Color Converter. If the site later adds a genuinely useful Design Tools category page, it can become an intermediate destination. Do not insert a category in the structured data alone when visitors cannot reach or understand that category on the actual website. #### Avoid invented or decorative steps Do not add unrelated high-value terms to breadcrumb names in the hope that markup will improve relevance. A category should reflect the page’s real place in the site. Likewise, valid JSON does not make an unsupported hierarchy accurate. Breadcrumbs supplement navigation; they do not replace useful titles, content, working links or a coherent archive. #### Validate on several route types Check a tool, article, project and top-level page after export. Confirm sequential positions, correct canonical destinations and visible agreement. Run a structured-data validation tool when preparing a public release, and inspect any search enhancement reports once data is available. Eligibility and accurate markup do not guarantee that a search engine will display a particular breadcrumb presentation. Sources: - [Google: breadcrumb structured data](https://developers.google.com/search/docs/appearance/structured-data/breadcrumb): Reference source. ### Build Controlled React Forms Without Fighting the Browser Canonical URL: https://ourjs.in/blog/react-controlled-forms/ Author: Nayan Kumar. Published: 2026-10-26. Category: React. Keep field state, validation timing and native form behavior aligned for predictable data entry. #### Choose what owns each field A controlled field receives its current value from React and reports edits through a handler. An uncontrolled field lets the browser maintain its current value and can be read when the form submits. Either approach can be useful. Choose one deliberately for each field instead of switching between undefined and a defined value as asynchronous data happens to arrive. #### Keep a draft example predictable For a project inquiry, initialize name, email and message as strings. Update each value from its corresponding input event and let the browser show the new value immediately. If a field receives a value prop without an appropriate update handler, typing may appear broken. Keep formatting transformations separate when they would unexpectedly move the caret or change what the person is still entering. #### Use the form’s native structure Associate visible labels with controls, keep meaningful name and autoComplete attributes, and use a submit button inside a form. A submit handler can prevent the default behavior when JavaScript owns the action, while still supporting Enter-key submission. Buttons for secondary actions should declare type=button so that clearing a preview does not accidentally send the entire form. #### Distinguish raw input from validated data An empty numeric field is a useful editing state even if the final value must be a positive integer. Preserve the editable text until parsing and validation are appropriate. The same distinction applies to dates and formatted identifiers. Forcing every keystroke into the final domain type can make deleting or correcting a value unexpectedly difficult. #### Show errors at a helpful time A field should not announce an error before the visitor has had a chance to complete it. Choose a validation policy such as blur, attempted submission or a carefully designed combination. Keep error text near the field and associate it programmatically where appropriate. A failed submission should retain the draft, and pending feedback should accurately reflect whether an operation is still running. #### Verify ordinary entry patterns Test typing, pasting, clearing, autocomplete and keyboard-only submission. Include a failed action followed by a successful retry, and check that the form does not reset prematurely. Confirm that a visitor can edit a partially entered numeric or email value. The best controlled form preserves the browser’s useful behavior while making application state explicit, rather than treating every edit as an opportunity to rewrite the input. Sources: - [React: input component reference](https://react.dev/reference/react-dom/components/input): Reference source. ### Build Reusable Components Around Behavior, Not Just Markup Canonical URL: https://ourjs.in/blog/reusable-component-contracts/ Author: Nayan Kumar. Published: 2026-10-26. Category: Frontend Engineering. Define ownership, events, accessibility and variation before turning repeated UI into an abstraction. #### Look for a shared responsibility Two pieces of UI can look similar while serving different interactions. Extracting them solely because their markup shares a border and a heading can create a component with many contradictory options. Start by asking what responsibility is truly repeated: presenting a project summary, collecting a labeled value or confirming an action. A useful abstraction gives that responsibility a clear name. #### Write representative usages first For a project summary component, sketch one usage with an image, one without an image and one with a long title. Decide which data is required and how navigation works. These examples expose whether the proposed API describes the feature naturally. If every call requires several exception flags, the common boundary may be smaller than the first design suggested. #### Specify state ownership A component can be controlled by its parent, own a local draft, or combine the two through a documented editing lifecycle. Avoid unclear hybrids where the parent supplies a value but the child also changes its private copy without reporting the change. Name callbacks after the intent they communicate, and include enough information that the parent does not need to inspect the component’s internal DOM. #### Make accessibility part of the contract A field wrapper must preserve labels, names, descriptions and useful native attributes. A disclosure must expose expansion state and keyboard behavior. These should not be optional extras added separately at each call site. Explain which responsibilities the component guarantees and which the caller must supply, such as meaningful link text or an appropriate alternative description for an image. #### Keep variations finite and meaningful Variants can express established design choices, such as compact and comfortable density. They should not become a replacement for every possible CSS declaration. Prefer composition when content structure genuinely changes, and preserve an escape hatch only when its cost is understood. A small explicit API is easier to maintain than a generic object that silently passes arbitrary behavior throughout the tree. #### Verify the abstraction at its boundaries Render realistic long content, empty optional content, disabled actions and multiple instances. Check events, focus movement and updates from the parent. Review whether a caller can create an invalid combination and whether that combination should be rejected by types or runtime validation. Reuse pays off when the component makes correct behavior easier across real screens, rather than merely reducing the number of repeated lines. Sources: - [React: passing props to a component](https://react.dev/learn/passing-props-to-a-component): Reference source. ### Build Social Sharing Cards That Match the Page Being Shared Canonical URL: https://ourjs.in/blog/open-graph-social-cards/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Keep Open Graph titles, image assets and canonical sharing URLs accurate across portfolio pages and articles. #### Treat sharing as its own surface A link preview is often the first representation someone sees outside the website. It needs a recognizable identity, a meaningful title and an image that stays readable at small sizes. This is related to search metadata but has its own fields and asset requirements. A successful sharing preview does not prove that the page’s indexing signals are correct. #### Set page-specific properties Open Graph defines properties including title, type, image and URL. A shared root image can provide a fallback, while article titles and destination URLs should describe the individual page. Be careful when inheriting a layout object: copying the homepage URL into every child page makes different articles appear to describe the same shared object. #### Design an original example card For a guide about release caching, use a simple composition with a short headline, a restrained brand mark and a diagram of HTML pointing to versioned CSS. Avoid a screenshot filled with tiny terminal text. Keep important words away from the edges so a platform crop has room to vary without removing the subject entirely. #### Publish accessible image assets Use a public absolute image URL with the correct content type and declared dimensions when supported. A local filesystem path or an image behind authentication will not work for a sharing crawler. Provide descriptive alternative metadata where appropriate. Compress the asset sensibly and confirm that its final filename matches the path used in the generated head tags. #### Expect preview caches Platforms can cache the metadata and image associated with a URL. Updating the website does not necessarily refresh every existing preview immediately. Inspect the live HTML and image response first, then use the platform’s supported inspection tools if needed. Renaming every asset without understanding which cache is stale can complicate maintenance without addressing the underlying metadata error. #### Test representative page types Check the homepage, a project, an article and a tool page. Compare their titles, URLs and image fields with the intended destination, and open each image directly. Test readability at a small display size as well as at the source resolution. A card should remain recognizable when shared, while the landing page should deliver the same subject and identity it promised. Sources: - [Open Graph protocol](https://ogp.me/): Reference source. ### Build Useful Tool Landing Pages Without Turning Them into Keyword Padding Canonical URL: https://ourjs.in/blog/seo-friendly-tool-pages/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Explain input, output, privacy, limitations and next steps so a tool page earns its own distinct place in a collection. #### Lead with the task Someone opening a tool page should quickly understand what input it accepts and what result it produces. Put the working controls near a clear title and short explanation. Avoid making visitors scroll through several paragraphs of promotional copy before reaching the utility. Content supports the task; it should not become an obstacle placed in front of it. #### Document the actual implementation Write instructions against the shipped behavior. An image compressor that exports WebP needs different guidance from a resizer that draws to exact dimensions. Mention whether aspect ratio is locked, whether transparency survives and where processing happens. These details create useful distinctions between neighboring tools that share a visual template but solve different problems. #### Include a small, safe example For a query-string parser, show an invented URL such as https://example.com/search?q=design&page=2 and explain the expected keys. Do not ask visitors to paste authentication links or sensitive customer data into an example. A concrete demonstration reveals whether the tool handles repeated parameters, empty values and URL encoding more clearly than a vague claim of simplicity. #### Answer genuine limitations FAQs should address decisions a visitor might face: supported formats, browser requirements, size limits or whether a generated QR destination can be changed. Do not write several versions of the same question just to repeat the tool name. If the browser cannot perform an operation reliably, describe the boundary rather than presenting an inaccurate success message. #### Link to useful neighboring resources Choose related tools and guides based on the workflow. A color converter can link to contrast checking; a JSON formatter can link to encoding guidance. Describe the page with appropriate structured data only when its properties reflect reality. Do not invent ratings, user counts or awards to make a simple utility appear more established. #### Check discoverability and completion Before publishing, verify a unique title and description, a correct canonical, an inbound archive link and accessible headings. Then complete one representative task and one invalid-input case. A page that passes metadata checks but produces an unusable download has not fulfilled its main promise. Maintenance should cover both the content explanation and the behavior it explains. Sources: - [Google: helpful content guidance](https://developers.google.com/search/docs/fundamentals/creating-helpful-content): Reference source. ### Button or Link? Choose HTML from the Interaction’s Purpose Canonical URL: https://ourjs.in/blog/button-vs-link-html/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Use links for destinations and buttons for actions so browser and keyboard behavior remain predictable. #### Ask what happens after activation A link takes the reader to a destination, including another route, a fragment or a downloadable resource. A button performs an action such as filtering cards, opening a menu or generating a result. Choose the element from that behavior first. The visual design can make either element look like a filled rectangle if that suits the interface. #### Use real destinations for navigation A project card that opens a case study should contain an anchor with a meaningful href. That supports opening in another tab, copying the address and normal browser navigation. An onClick handler on a div can imitate a basic visit but misses those established behaviors unless you recreate more of the browser’s interaction model. #### Give buttons explicit form behavior Inside a form, a button may submit by default. A secondary action such as Clear draft or Preview snippet should use type="button" if it must not submit. The actual submission control can use type="submit". This small distinction prevents accidental sends or validation attempts when a user only intended to adjust the interface. #### Preserve useful accessible names Use labels that explain the destination or action: Download résumé, View project, Generate password. An icon can accompany the label without replacing its meaning. If a control must be icon-only, provide a clear accessible name and a visible focus treatment. Generic repeated labels become ambiguous when presented outside their surrounding visual card. #### Avoid nested interactive controls Do not place a button inside a link that already makes the whole card clickable. Competing interactive descendants create confusing activation and keyboard behavior. Choose one primary card link, then put any separate action beside it in a clear structure. The reader should be able to tell which control will respond before clicking. #### Test the browser features you expect Open a project link in a new tab, copy its destination, activate an action with Space and submit a form with the keyboard. Check that disabled actions are really disabled and that a download serves a real file. Correct semantics are useful because they align the implementation with behavior people already know, across more than one input method. Sources: - [MDN: the button element](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/button): Reference source. ### Cancel Stale Fetch Requests with AbortController Canonical URL: https://ourjs.in/blog/fetch-abort-controller/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Keep search results and navigation reliable by cancelling obsolete requests and ignoring outdated responses. #### Recognize the stale-response problem A visitor types a city name, then quickly changes it. The first search might finish after the second and overwrite the correct results with older data. This problem is about ownership of a result, not simply network speed. Each request needs a relationship to the input and screen state that made its response relevant. #### Create a controller for each operation Construct an AbortController, pass its signal to fetch, and keep the controller associated with that request. When a new search replaces the old one, abort the previous controller before starting the replacement. Do not reuse a signal that has already been aborted. A fresh operation needs a fresh controller and an independently managed lifecycle. #### Separate cancellation from a real error An aborted search usually means the user changed direction, so showing a red network failure would be misleading. Handle an expected abort quietly, while still surfacing a genuine connection or server problem. Keep the loading state associated with the latest operation; an older request finishing its finally block must not make a newer request appear complete. #### Protect against outdated completion too Cancellation is useful, but a response may already have reached a stage where application processing is running. A request sequence number or matching query check can ensure that only the current operation updates the screen. For example, assign each search an increasing identifier and compare it before committing results. This complements cancellation rather than replacing its resource-saving purpose. #### Connect cleanup to navigation A component that starts a request during its lifecycle should stop or invalidate it when the component leaves the screen. The same applies when an input dependency changes. Event-owned requests can keep their controller in a ref or other stable operation record. Document the behavior so future code does not accidentally allow two competing writers to the same result state. #### Test with deliberately reversed timing Use local delayed responses for two different queries and make the older query finish last. Confirm that the final heading, result list and loading indicator all describe the new query. Navigate away during a request and check for unnecessary updates. Then test a genuine failure to ensure that distinguishing cancellation has not hidden every kind of error. Sources: - [MDN: AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController): Reference source. ### Canonical URL Mistakes That Hide Behind a Working Page Canonical URL: https://ourjs.in/blog/canonical-url-mistakes/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Find mismatched hosts, copied canonical tags and pagination mistakes before they become conflicting search signals. #### Define the preferred address Choose a consistent public scheme, hostname and path convention for each page. A canonical tag expresses the preferred representative of duplicate or substantially similar content; it is not a shortcut for removing unrelated pages. Document the URL policy so navigation, metadata and sitemaps use the same address rather than relying on individual authors to guess. #### Watch inherited layout metadata A shared root canonical is convenient until every child page accidentally points to the homepage. The pages still render and their links still work, which makes the problem easy to miss in visual reviews. Generate or override the canonical at the page level, especially when one route template renders many different tools or articles. #### Follow an example through the site Suppose the intended address is https://example.com/tools/json-formatter/. Its breadcrumb, sitemap and internal cards should use that path. A canonical pointing to https://www.example.com/tools/ creates a different instruction. Compare the final response after redirects, not the URL pasted into a browser before the hosting platform normalizes it. #### Separate duplicates from distinct pages A filtered view that changes only ordering may represent a duplicate, while the second page of an article archive contains different entries. Do not canonicalize every archive page to the first simply because the layout is shared. Examine the main content and purpose of the URL before applying a blanket rule to the route family. #### Do not use canonical as access control Canonicalization does not make confidential data private and is not a guaranteed removal mechanism. Protect private resources with appropriate authentication. For public pages that should not be indexed, investigate the appropriate indexing directive instead. Mixing unrelated concerns into one canonical policy produces a site that is harder to reason about and debug. #### Verify signals after deployment Extract canonical URLs from the exported HTML and compare them with the sitemap. Test their status, hostname and trailing slash behavior on the actual host. Search Console can show the canonical Google selected, which may differ from the declared preference. When a mismatch appears, investigate duplicated content and competing signals rather than repeatedly changing the tag without evidence. Sources: - [Google: canonicalization](https://developers.google.com/search/docs/crawling-indexing/canonicalization): Reference source. ### Check Color Contrast in the Actual Interface, Not Just the Palette Canonical URL: https://ourjs.in/blog/color-contrast-checking/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Evaluate text and background pairs, account for real component states, and keep color from becoming the only signal. #### Start with a foreground and background pair A palette does not pass or fail contrast as a group. Each use creates a specific relationship. Gold might work as a background behind plum text while being unsuitable for small lettering on silver. List the combinations used by body copy, buttons, captions, inputs and links before deciding which colors need to change. #### Apply the appropriate threshold WCAG’s minimum text contrast criterion generally calls for 4.5:1 for normal text and 3:1 for large text, with defined exceptions. Do not round a value up to claim it meets a threshold. A numeric pass also does not guarantee that an extremely thin font or tiny caption will feel comfortable to read. #### Measure the rendered colors Use the colors actually produced by the interface, including opacity and the effective background. A plum label at partial opacity on a silver panel does not have the same contrast as solid plum. Gradients and images add variation, so check the lowest-contrast area behind the text or provide a reliable solid surface. #### Test a concrete button example Suppose a primary button uses a bright pink fill. Instead of assuming white text is the standard choice, compare white and near-black labels against that exact fill. Then repeat the calculation for hover and disabled states. The more readable choice may preserve the intended brand color without requiring the background to become darker or less distinctive. #### Add cues beyond color A form error needs a written explanation, a selected filter needs an identifiable state, and an inline link benefits from a non-color cue such as an underline. Contrast helps the signal remain visible, but it does not explain what the signal means. Design shape, text and state indicators as part of the same interaction. #### Keep a practical review list Check body text, secondary text, form placeholders, focus indicators and text inside every product-card variation. Inspect them on both light and dark page themes. Record the real pair values with the component so later changes can be reviewed. Automated contrast tools are helpful, but a manual pass is still needed for images, overlays and changing interaction states. Sources: - [W3C: understanding minimum text contrast](https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html): Reference source. ### Choose React List Keys That Preserve the Right Identity Canonical URL: https://ourjs.in/blog/react-list-keys/ Author: Nayan Kumar. Published: 2026-10-26. Category: React. Use stable record identity so filtering and reordering do not move input state to the wrong row. #### Think about identity rather than warnings A key helps React relate a rendered child to its counterpart across changes in a collection. Removing a console warning is only the visible symptom. The real design question is which item should preserve its local state when the list changes. Choose a key that represents the record’s stable identity, rather than its current position or its appearance during one render. #### Try an editable task example Suppose three rows each contain a task name and an editable note. The visitor types a note in the second row, then the first row is removed. With position-based keys, the remaining positions may inherit state associated with a different task. Stable task identifiers keep the note attached to the intended record as the visible list becomes shorter. #### Generate identifiers at creation time New local records can receive an identifier when they are created, and imported records can use a reliable existing key. Do not generate a fresh random key while rendering. A changing key tells React that the child is a different identity, which can reset inputs, focus and other local behavior on every update. Identifiers should be part of the data lifecycle. #### Keep uniqueness in the relevant collection Sibling children need distinct keys within their rendered list. A key does not need to be globally unique across every list on the page, but collisions among siblings make identity ambiguous. If external records lack a single stable identifier, define a meaningful composite key and document its assumptions. A display label may not be unique or stable enough for that role. #### Use resets deliberately Sometimes a changing key is exactly the desired behavior, such as starting a fresh editor for a newly selected document. That should be an intentional reset boundary. Do not depend on accidental key changes to clear errors or refresh data. Also pass an identifier as an ordinary prop if the child needs to read it; the reconciliation key is not an ordinary component field. #### Verify state across structural changes Test inserting at the beginning, sorting, filtering, deleting and restoring an item. Type into a row before each action and watch both the text and keyboard focus afterward. Include duplicate labels to ensure identity does not depend on a human-readable name. A correct list keeps persistent state with the record and resets it only where the interaction explicitly calls for a new identity. Sources: - [React: rendering lists](https://react.dev/learn/rendering-lists): Reference source. ### Container Queries: Let Reusable Cards Adapt to Their Actual Space Canonical URL: https://ourjs.in/blog/container-query-components/ Author: Nayan Kumar. Published: 2026-10-26. Category: CSS. Build components that respond to a sidebar or content column instead of assuming the viewport tells the whole story. #### Find the component’s real constraint A project card can appear full-width on one page and in a narrow sidebar on another. A viewport media query sees the same browser width in both cases, even though the card has very different room. Container queries let the component respond to the space supplied by its surrounding layout instead. #### Create a useful containment boundary Wrap the component in an element with container-type:inline-size when you want to query its inline dimension. The component inside can then respond through an @container rule. Choose a wrapper whose size is determined by the surrounding layout. Applying containment without considering how that wrapper receives its width can produce an unexpectedly collapsed or constrained region. #### Start with the narrow layout Build the card as a vertical stack by default: image, title, description, then action. At an appropriate container width, change the inner card to a horizontal layout. For example, an @container rule above 34rem might allow a thumbnail beside the text. The component remains usable even when the query is unavailable or never matches. #### Name containers when context gets complicated Nested layouts can contain multiple queryable ancestors. A container name such as project-slot makes the intended boundary easier to identify. Use that name in the query when a generic nearest-container rule would be ambiguous. Names should describe a stable layout responsibility, rather than incidental page coordinates or a specific screen resolution. #### Avoid moving the problem into typography A horizontal card is only helpful if the image and text both have enough space. Test long titles and descriptions before increasing the number of columns. A smaller font should not be the automatic response to a cramped component. Often the correct behavior is to remain stacked longer and allow the card to grow vertically. #### Test the component in several hosts Place the same card in a wide content column, a sidebar and a two-column project grid. Resize those hosts independently when possible. Check that the chosen ancestor is the one being queried and that the fallback is complete. Container queries work best when they make a component less dependent on where it happens to be embedded. Sources: - [MDN: CSS container queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Containment/Container_queries): Reference source. ### Create Internal Links Around the Reader’s Next Useful Question Canonical URL: https://ourjs.in/blog/internal-linking-topic-clusters/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Connect guides and tools with descriptive links that form useful paths rather than artificial keyword clusters. #### Start from a real relationship Two pages deserve a link when one helps someone act on or extend the other. An image-format comparison naturally connects to an image converter; an unrelated password generator does not become relevant merely because both pages belong to the same site. Map relationships around tasks and questions before adding a generic related-content box everywhere. #### Use descriptive link text A linked phrase should give a reasonable clue about its destination. Compare Read more with Compare WebP, JPEG and PNG. The second phrase lets someone decide whether the detour is worthwhile. Keep wording natural in the sentence and avoid forcing the exact same target phrase into every article that mentions a broadly related subject. #### Design a practical path Consider a visitor preparing a portfolio screenshot. A resizing guide links to the image resizer; the tool explains dimensions and links to compression guidance; that article links to format selection. Each step answers a different question. The sequence creates a useful workflow without requiring an artificial parent article that repeats the same introduction three times. #### Expose links as actual links Use anchor elements with href destinations for navigation. A click handler on a decorative card may work for one pointer interaction while making discovery, keyboard use or opening a new tab more difficult. Keep the title and linked area clear, and avoid nesting separate interactive controls inside one large card link. #### Prevent orphaned and stale pages When publishing a new guide, add at least one appropriate path from an archive or existing article. When removing a page, inspect references to it instead of leaving broken recommendations behind. Large collections benefit from route audits that compare published records, inbound links and sitemap coverage. These checks reveal structural gaps that a homepage-only review will miss. #### Review the journey as a reader Open a few articles without using site search and follow the recommended next steps. Ask whether each destination adds information, whether the anchor describes it, and whether returning is easy. Keep the set focused. A small number of relevant choices usually communicates more intent than a long footer stuffed with every phrase the site hopes to rank for. Sources: - [Google: crawlable links and anchor text](https://developers.google.com/search/docs/crawling-indexing/links-crawlable): Reference source. ### Create Print Styles for Articles and Portfolio Pages Canonical URL: https://ourjs.in/blog/print-stylesheets/ Author: Nayan Kumar. Published: 2026-10-26. Category: CSS. Make the browser’s print view useful by removing decorative motion and preserving the information someone wants to keep. #### Choose what the printout is for A printed article should preserve its explanation, headings and useful references. A printed portfolio project should identify the work and show its relevant evidence. Neither needs a sticky menu, a custom cursor or a floating animation control. Begin by deciding what a reader would reasonably want to carry away from the current page. #### Add a focused print layer Use an @media print block to adapt the existing document instead of creating an unrelated duplicate of every page. Reset decorative backgrounds when they impair readability and use a straightforward text color. Keep changes scoped to print so they do not alter the live design. A short, intentional stylesheet is easier to maintain than scattered print exceptions. #### Remove fixed and moving furniture Hide site navigation, motion controls and purely decorative hero layers from the printed view. Reset sticky and fixed positioning on content that should flow normally. Stop animations and transitions. Elements designed to remain over the viewport can repeat awkwardly or obscure text when a browser lays the document out across multiple pages. #### Manage page breaks carefully Keep a short project card or a heading with its following content where practical, using appropriate break rules. Do not forbid breaks inside a very long article section, because it may be taller than a page. Let paragraphs flow while protecting small units that become confusing when split, such as an image and its short explanatory caption. #### Preserve useful destinations A printed link label such as Read more may lose its destination. Consider showing URLs for important external references when that improves the document, but avoid appending a long tracking URL after every navigation link. Check whether collapsed disclosures contain necessary information; a print treatment may need to expose their answers rather than retaining the interactive presentation. #### Review the browser preview Open print preview with common paper sizes and inspect the first, middle and last pages. Look for cropped code, missing diagrams, excessive blank space and orphan headings. Try saving to PDF as well as previewing paper output. Print support is successful when the exported reading experience communicates the same useful information without depending on a screen-only interface. Sources: - [MDN: printing with CSS](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Media_queries/Printing): Reference source. ### CSS Logical Properties: Write Layout Rules Around Reading Direction Canonical URL: https://ourjs.in/blog/css-logical-properties/ Author: Nayan Kumar. Published: 2026-10-26. Category: CSS. Use inline and block dimensions to make component spacing easier to adapt across writing directions. #### Separate physical edges from logical flow Left and right describe physical sides. Inline start and inline end describe positions relative to the writing direction. In an English horizontal layout, inline start is usually the left side; in a right-to-left layout it changes. Logical properties let a component express that relationship instead of embedding one language’s direction into every spacing rule. #### Start with common spacing rules Replace directional spacing where the intention is relative to the text. For example, padding-inline can give a card equal space on both inline edges, while margin-block-end separates it from following content. A small set of these properties can make a component’s purpose clearer even before the site supports more than one language. #### Use a concrete icon-and-label example A button with an icon before its label needs space between those two items, not necessarily a margin on the physical right edge of the icon. A flex gap often expresses that relationship directly. Where a one-sided margin is appropriate, choose margin-inline-end if the space should follow the icon in the reading direction. #### Keep truly physical positioning physical Not every left value should become inline-start. A decorative illustration may be intentionally anchored to the physical left of a photograph regardless of language. Review the design requirement before converting it. Mechanical replacement can move art direction unintentionally while leaving the genuinely language-dependent parts of the interface unchanged. #### Check dimensions and borders together Logical concepts also apply to sizing and border placement. Inline-size can describe a control’s extent along the inline axis, and border-inline-start can mark a callout’s beginning edge. Avoid mixing physical and logical properties on the same responsibility without checking which declarations win in the cascade and how they behave under a different direction. #### Verify with a changed direction Test the component in an RTL wrapper and inspect labels, icons, alignment and spacing. This does not prove the whole page is correctly localized; text, navigation order and cultural expectations still need review. It does reveal rules that accidentally assume every reader moves left to right and makes future adaptation more deliberate. Sources: - [MDN: CSS logical properties and values](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Logical_properties_and_values): Reference source. ### Debounce vs Throttle for Real Interface Events Canonical URL: https://ourjs.in/blog/debounce-vs-throttle/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Choose the right event scheduling strategy for search, scroll feedback and responsive controls. #### Begin with the interaction requirement Frequent events do not all need the same treatment. A search request often benefits from waiting until typing pauses. A visible progress indicator needs periodic updates while movement continues. Ask whether the interface needs the latest quiet moment, a controlled stream of updates, or a repaint-aligned update. That question is more useful than choosing a utility by habit. #### Debounce a replaceable action A trailing debounce resets its timer whenever a new event arrives and runs after a quiet interval. For example, a category search can update the input immediately while delaying its remote lookup. If the user types new text before the timer fires, discard the pending lookup. Keep the field responsive; debounce the expensive effect rather than the text displayed under the cursor. #### Throttle ongoing feedback A throttle limits how often work runs during a continuing stream. A drag readout might refresh at a controlled interval while still reflecting progress. Decide whether the first event, the last event, or both should be represented. Without that decision, the displayed final position can lag behind the actual pointer even though the implementation appears to reduce event volume. #### Use animation frames for visual work For a scroll-linked transform, requestAnimationFrame can coalesce repeated events into one pending visual update. Read the latest position when that update runs. This does not make expensive work free, nor does it replace a longer scheduling policy for network calls. Keep DOM reads and writes organized so the scheduling change does not introduce unnecessary layout calculation. #### Clean up timers and stale closures Cancel pending timers when their owning component disappears or when the callback contract changes. In a framework, recreating a debounced function on every render can leave several timers alive or preserve old values accidentally. Keep operation ownership clear, and pass the relevant latest input explicitly when practical. Debouncing also does not prevent stale network responses; handle those separately. #### Verify the final event is represented Test fast typing, long pauses, continuous scrolling and stopping abruptly. Confirm that the last query or position reaches the interface. Test keyboard input as well as pointer gestures, and consider whether delayed feedback needs an accessible pending message. Compare the number of expensive calls before and after, while checking that the interaction remains understandable rather than merely quieter. Sources: - [MDN: debounce](https://developer.mozilla.org/en-US/docs/Glossary/Debounce): Reference source. ### Debug Horizontal CSS Overflow Without Hiding the Evidence Canonical URL: https://ourjs.in/blog/css-overflow-debugging/ Author: Nayan Kumar. Published: 2026-10-26. Category: CSS. Find the element that makes a page wider than its viewport and fix the actual sizing problem. #### Confirm the symptom A page that slides sideways on a phone usually has at least one element extending beyond its intended container. Compare the document’s scroll width with its client width, then inspect the visible edges. Do this at the width where the issue appears. A desktop screenshot may conceal a problem caused only by a long word or narrow layout. #### Inspect likely offenders first Common causes include fixed-width images, wide code blocks, unbroken URLs and grid items whose minimum size prevents shrinking. Decorative transformed layers can also extend beyond the page. Temporarily outline candidate elements in developer tools and inspect their bounding boxes. Find the specific element rather than immediately adding overflow-x:hidden to the body. #### Distinguish sizing from text wrapping If a flex or grid child refuses to shrink, min-width:0 on the correct wrapper may be relevant. If the box fits but an unbroken token spills outside it, a wrapping rule may be the right fix. A table or code sample may instead need a deliberate local horizontal scroller so its information is not destroyed. #### Check viewport-based dimensions An element set to 100vw can behave differently from width:100% inside a padded page, depending on the containing context and scrollbar. Add padding and borders to the calculation as well. A hero background that should bleed to an edge may need a different structure from a content panel that must stay inside the main container. #### Clip decoration at its own boundary A large orbital illustration can be safely clipped by a dedicated decorative wrapper if it carries no necessary content. Avoid clipping the entire page as a general repair, because that can hide focus outlines, offscreen controls and meaningful content. The clipping boundary should express the intended visual composition, not conceal an unexplained layout defect. #### Retest the content that broke it After changing the rule, retry the original long title or code token and resize through neighboring widths. Test browser zoom and keyboard focus around the repaired element. Verify that there is no page-wide overflow and that any intentional local scroller remains discoverable. A robust fix explains why the element now fits rather than merely making the scrollbar disappear. Sources: - [MDN: overflow](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/overflow): Reference source. ### Deploy a Next.js Static Export Without Assuming a Node Server Exists Canonical URL: https://ourjs.in/blog/nextjs-static-export-hosting/ Author: Nayan Kumar. Published: 2026-10-26. Category: Next.js. Plan routes, browser features and hosting behavior around the files produced by a static build. #### Understand the deployment boundary A static export produces files that a web server can deliver without running a Next.js application process for each request. That changes which features are available after deployment. Build-time rendering and browser interactivity can work well together, but request-time server logic cannot appear simply because development mode supported it on your machine. #### Choose routes that can be built Public content with known records is a natural fit. Generate the slugs for tool and article routes during the build, and ensure every intended page appears in the output. If a route depends on a user’s cookie or a server action, decide whether that requirement needs a different hosting model rather than hiding it behind a static-looking interface. #### Map URLs to exported files Suppose the site uses trailing slashes and exports a guide to out/blog/release-checklist/index.html. The host must serve that file when someone opens /blog/release-checklist/ directly. Test direct deep links, not only client navigation from the homepage. Configure an actual missing-page response for unknown paths instead of returning the homepage with a successful status. #### Keep browser features explicit A browser-only image converter can remain interactive after export because processing happens on the visitor’s device. A mailto contact form can prepare a message but does not become a submission backend. Document these distinctions honestly. Browser APIs should run in effects or event handlers, while initial rendering still needs to produce valid markup during the build. #### Deploy the complete artifact Upload the contents of the generated output directory, including framework assets and metadata files. Copying only HTML can leave a page readable but noninteractive. Copying only a development build is a different failure. Keep a recognizable release identifier and retain the previous artifact so you can identify what is live and restore it if necessary. #### Verify on the target host Check the homepage, a deep tool URL, an article, a downloaded asset, robots.txt and the sitemap. Confirm content types and cache behavior, then exercise at least one browser utility. Run the same checks after uploading, because local success does not establish that the host maps paths correctly. Use the static-export documentation for the installed Next.js version when choosing unsupported features and workarounds. Sources: - [Next.js: static exports](https://nextjs.org/docs/app/guides/static-exports): Reference source. ### Derive React Display Data Instead of Synchronizing Copies Canonical URL: https://ourjs.in/blog/react-derived-state/ Author: Nayan Kumar. Published: 2026-10-26. Category: React. Keep one source of truth for filters, totals and labels, reserving effects for external synchronization. #### Identify information that already exists A selected category, search text and a list of projects are sufficient to determine the visible projects. Storing the visible list separately creates another value that must stay synchronized with all three inputs. Before adding state, ask whether the value can be calculated from information already available during rendering. Derived values often make both the implementation and its failure modes smaller. #### Follow a concrete filter screen Imagine a portfolio with category buttons and a text field. Keep the category and query in state, then filter the source projects while rendering. The displayed count can come from that filtered array. There is no need for separate effects that update visibleProjects and visibleCount after each input changes, which would temporarily allow the count and list to disagree. #### Separate user intent from a calculation A draft search field may deliberately differ from a submitted search query. Those are two different pieces of user intent, so storing both can be reasonable. A count calculated from the submitted results is different: it is simply a consequence of existing data. Name these responsibilities clearly so a rule against redundant state does not erase meaningful intermediate steps in the interaction. #### Optimize expensive derivation only when needed Filtering a small collection is usually straightforward. If profiling shows that a particular calculation is expensive and reruns unnecessarily, memoization may help cache it under the right dependencies. Memoization should preserve the same result semantics, not become the only reason the component works correctly. Avoid adding a network of caches before understanding the actual cost of the interaction. #### Reset state through clear ownership A detail editor may need a fresh draft when the selected record changes. Decide whether that means a new component identity, an explicit reset action or a controlled parent value. Copying every prop into local state and continuously synchronizing it through an effect can overwrite the visitor’s edits. Model the editing lifecycle, including when unsaved work should be kept or discarded. #### Verify coupled values together Change the category, clear the query, replace the source list and open a different record. Confirm that displayed totals, empty states and highlighted filters all agree in the same render. Look for effects whose only purpose is assigning another derived value. Removing those effects should simplify behavior while preserving the deliberate distinction between saved data, draft input and submitted intent. Sources: - [React: you might not need an effect](https://react.dev/learn/you-might-not-need-an-effect): Reference source. ### Design a Frontend CI/CD Pipeline Around Evidence and One Artifact Canonical URL: https://ourjs.in/blog/cicd-build-test-deploy/ Author: Nayan Kumar. Published: 2026-10-26. Category: DevOps. Separate installation, validation, build, publication and post-deployment checks so release failures have a clear location. #### Make each stage answer a question A pipeline is easier to debug when its stages have distinct purposes. Dependency installation establishes the environment, checks assess the change, the build produces the artifact, publication makes it available, and verification tests the deployed result. Combining everything into one opaque shell command hides which promise failed and makes partial success difficult to interpret. #### Use reproducible inputs Commit the dependency lockfile and select a supported runtime deliberately. Install from that lockfile in automation rather than resolving a different dependency tree on each run. Record the source revision with the output. This does not guarantee every dependency is suitable, but it makes the build’s inputs inspectable and helps distinguish an application change from an environment change. #### Choose checks that match the site For a static portfolio, useful checks can include TypeScript validation, route generation, metadata coverage, internal links and a representative interactive workflow. A formatting-only change does not justify inventing an unrelated test suite. Conversely, a tool that transforms user data needs behavioral examples, not only a successful compiler run. Keep checks proportional to what can actually break. #### Promote a concrete example release Imagine a journal deployment that adds ten guides. The build should produce all ten detail pages, update archive links and include their canonical URLs in the sitemap. Package that exact output and publish it. Rebuilding after approval with different inputs breaks the connection between the artifact reviewed in testing and the one visitors receive. #### Protect publication from races Use separate permissions for reading source and publishing where the platform allows it. Coordinate concurrent runs so an older build cannot unexpectedly replace a newer release. Keep credentials out of logs and client bundles. A deployment job’s authority should match its destination rather than inheriting broad account access simply because that was easiest to configure. #### Close the loop after deployment Check the public homepage, a deep route, metadata files and one primary user task. Record the deployed revision and make rollback instructions accessible. A green upload step proves that files were transferred, not that the website serves them correctly. Post-deployment verification turns the pipeline from a sequence of commands into a traceable release process with observable outcomes. Sources: - [GitHub: custom Pages workflows](https://docs.github.com/en/pages/getting-started-with-github-pages/using-custom-workflows-with-github-pages): Reference source. - [GitHub: concurrency](https://docs.github.com/en/actions/concepts/workflows-and-actions/concurrency): Reference source. ### Design a Mobile Navigation Menu That Stays Easy to Use Canonical URL: https://ourjs.in/blog/mobile-navigation-design/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Build a straightforward navigation disclosure with reliable focus, state and responsive behavior. #### Keep the navigation hierarchy small A personal portfolio usually needs a few clear destinations: work, about, journal, tools and contact. Start with those priorities instead of hiding a sprawling desktop sitemap behind a small icon. Short, distinct labels help someone understand the available routes quickly, especially when the menu becomes the main visible content on a phone. #### Use a button to open the panel The toggle performs an action, so use a button with a clear accessible name. Connect it to the menu panel through aria-controls and keep aria-expanded synchronized with the open state. A generic icon alone does not explain its purpose to every reader. The icon can change visually while the button’s label describes Open navigation or Close navigation. #### Keep hidden links out of the journey A panel moved offscreen with a transform may still contain keyboard-focusable links. Use an appropriate hidden or inert state when it is closed, and make sure the visibility transition does not leave a contradictory intermediate state. The closed menu should not create unexpected Tab stops between the visible header and the main content. #### Choose disclosure behavior deliberately A simple navigation panel is different from a modal dialog. It can follow the ordinary document flow without trapping focus, provided the interaction remains understandable. Escape is a useful way to close it and return to the toggle. If the design makes the panel truly modal, implement and test the additional modal requirements rather than borrowing only the appearance. #### Handle routes and resizing Close the menu after someone chooses a destination. If navigation happens through a client router, update the state when the pathname changes as well as when a link is clicked. Resize from mobile to desktop and back to catch panels that retain an old open state or create duplicated visible navigation groups. #### Test the menu as a real route Open it with a keyboard, follow a link, return with browser history and reopen it. Try enlarged text, a long translated label and a narrow viewport. Ensure the panel can scroll if its content exceeds the screen height. The final menu should make moving around the portfolio easier, without introducing a separate navigation puzzle. Sources: - [MDN: keyboard accessibility](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Guides/Understanding_WCAG/Keyboard): Reference source. - [MDN: the button element](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/button): Reference source. ### Design Angular Component Inputs as Clear Public Contracts Canonical URL: https://ourjs.in/blog/angular-components-inputs/ Author: Nayan Kumar. Published: 2026-10-26. Category: Angular. Keep required values, defaults and parent-owned state explicit when building reusable Angular components. #### Think of an input as an API An Angular component input is a public agreement with its parent. It should communicate what information the component needs and which variations it supports. Begin with a concrete usage instead of adding optional inputs for every possible future design. A focused contract is easier to validate, document and change without surprising other screens that use the component. #### Separate essential values from defaults A project card may require a project record while allowing a compact appearance with a sensible default. In signal-based inputs, a required input expresses the expectation that a template caller supplies that value. An optional input can intentionally include absence in its type. Do not invent an empty object that merely silences a missing-data problem while leaving the renderer with incomplete information. #### Read signal inputs through their interface Signal-based inputs are read by calling the input signal. Treat the resulting value as parent-provided data rather than an invitation to mutate the parent’s object. Derive a presentation label through a computed value when appropriate. This keeps the distinction between external input and internal view state visible, which becomes especially useful when the same card appears in several independently changing lists. #### Use outputs for requested changes For a selectable card, the child can emit an intent such as the selected identifier while the parent remains responsible for the authoritative selection. Avoid changing an input object in place to communicate upward. That hidden mutation can make the parent’s state flow difficult to follow. Document whether the component is controlled by its parent or owns an independent local draft. #### Keep transforms small and predictable Input transforms can normalize an accepted representation, but they should not become a hidden place for network activity or unrelated state changes. If a component accepts a wider input shape for convenience, explain the normalized internal value. A transformation that silently changes meaningful content can make debugging harder because the parent and child appear to be discussing different data. #### Verify from the consuming template Render the component with minimum required data, optional defaults and updated parent values. Check that required values are enforced by the project’s Angular tooling, and verify that a child interaction emits the expected event without mutating the input. Include missing optional imagery and long labels. Review the template as documentation: it should explain the component’s role without requiring knowledge of private implementation details. Sources: - [Angular: accepting data with input properties](https://angular.dev/guide/components/inputs): Reference source. ### Design API Loading, Empty and Error States Separately Canonical URL: https://ourjs.in/blog/frontend-api-error-states/ Author: Nayan Kumar. Published: 2026-10-26. Category: Frontend Engineering. Give each request outcome a truthful interface and make retries preserve the visitor’s work. #### Describe what the application actually knows Loading means a result is not ready, empty means a successful result contains no matching records, and error means the application could not obtain a trustworthy result. These are different claims. A blank table with No results is misleading when the request failed. Model the alternatives before designing their visual treatment so the interface remains honest when conditions are less than ideal. #### Check HTTP outcomes explicitly A fetch promise can resolve with an HTTP error response, so inspect response.ok or the relevant status before treating the body as successful data. Parsing can also fail independently of the status code. Keep transport, response interpretation and application validation distinguishable in the code. That separation makes it possible to show a useful explanation without guessing which stage went wrong. #### Follow a project search example For a query that returns no matches, keep the query visible and offer to clear filters or try another term. For a request that fails, explain that projects could not be loaded and provide a retry. When older valid results remain on screen, label their relationship to the pending request clearly. A spinner should not make outdated rows appear to answer the newest query. #### Preserve input and prevent conflicting actions A failed save should normally retain the draft that took time to enter. Disable or coordinate actions that would create duplicate requests, while leaving safe navigation and correction available. A retry should use a clearly defined current input snapshot. If the original operation may already have reached the server, retry behavior may require idempotency support rather than another identical button click. #### Make diagnostics useful without exposing internals A visitor needs a concise explanation and next step, not a raw stack trace or a complete server response. Developers may need a request identifier and the failing stage. Avoid logging passwords, tokens or full personal records. Keep cancellation separate from failure when the user simply changed a query or left the screen intentionally. #### Verify each state as a real scenario Exercise a delayed success, an empty response, a non-success status, malformed data and an unavailable network. Retry after failure and change input while an earlier request is pending. Check keyboard access and announcements for changed feedback. The screen should explain whether the person should wait, correct something, retry or change the query, rather than displaying one generic placeholder for every outcome. Sources: - [MDN: using the Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch): Reference source. ### Design CloudFront Cache Policies Around Response Variants Canonical URL: https://ourjs.in/blog/cloudfront-cache-policies/ Author: Nayan Kumar. Published: 2026-10-26. Category: AWS. Choose cache-key inputs and time-to-live settings by asking which request differences actually change the response. #### Start with the response contract A cache key identifies which stored response can satisfy a request. Before choosing headers, cookies and query parameters, decide which of those values actually change the content. Including every available value can fragment reuse unnecessarily. Excluding a value that changes the response can serve the wrong representation. The right policy follows the application’s behavior rather than a universal maximum-caching rule. #### Separate request forwarding from variation A service may need a request value at origin without requiring every value to create a distinct cached object. CloudFront separates relevant policy concepts, so read their responsibilities carefully. Do not assume that forwarding a header automatically means it is included in the cache key, or that a high cache-hit ratio proves the returned responses are correct. #### Use a practical static-site example Suppose /assets/logo.a1.svg is identical for all visitors. Varying its key by every analytics query parameter or unrelated cookie creates multiple entries for the same bytes. Conversely, an endpoint that produces different output for a language query requires a deliberate variation strategy. Classify paths and behaviors so a broad asset policy does not accidentally cover personalized application responses. #### Choose expiration boundaries deliberately The policy’s minimum, default and maximum TTL settings interact with response caching headers. Review the actual configured values and documented behavior instead of assuming the origin always has the final word. Use a short-lived or revalidated document policy when releases need to update HTML promptly, while versioned assets can usually support more reuse under an appropriate policy. #### Account for compression variants Compressed response handling is part of cache configuration, not simply a checkbox promising faster pages. Ensure the supported content-encoding behavior matches the origin and delivery service setup. Check that clients receive a representation they can decode and that uncompressed requests still work. Inspect response headers and transferred bytes rather than inferring effectiveness from a configured feature name. #### Test correctness before tuning hit rate Prepare requests that should share a representation and requests that should differ. Compare their response content, cache indicators and origin behavior. Repeat the exercise after changing a policy, then check release propagation. A useful cache policy reduces unnecessary origin work while preserving the distinctions the application needs; hit rate alone cannot reveal a privacy mistake or a stale document served efficiently. Sources: - [AWS: cache policies and cache keys](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html): Reference source. ### Design Reduced-Motion Modes That Still Feel Complete Canonical URL: https://ourjs.in/blog/reduced-motion-design/ Author: Nayan Kumar. Published: 2026-10-26. Category: Animation. Keep content, hierarchy and feedback intact when people prefer less movement or switch animation off. #### Identify movement that is optional Parallax, floating illustrations, looping decorations and large assembly transitions can add character, but they are not the content itself. Separate them from feedback required to understand a task. A download becoming ready still needs a clear status message when motion is disabled, even if the spinner and celebratory movement disappear. #### Listen to the platform preference The prefers-reduced-motion media query exposes a request to reduce nonessential motion. Use it in CSS to simplify decorative animation and in JavaScript before starting animation loops. Checking only CSS is insufficient when a script continues updating transforms in the background or uses an animation API that your styles do not directly control. #### Choose calmer substitutes A reduced-motion mode does not need to become an unfinished screen. Replace a long sliding panel transition with an immediate state change, keep a hero illustration assembled, and remove depth movement from background layers. The same typography, spacing and content should communicate the design even when none of the elements travel through space. #### Offer a persistent page control An on-page motion switch can be useful in addition to the operating-system setting. Give it a clear accessible name and expose its state. Save only the preference if persistence is needed, and handle unavailable browser storage gracefully. A preference control should keep working even when localStorage is blocked or a browser is in a restrictive mode. #### Do not hide content behind entrances A reveal effect should progressively enhance content that already exists. If the stylesheet starts every article at opacity:0 and JavaScript fails, the page becomes blank. Render a readable baseline and add movement when it is available. This approach also makes printing, searching and navigating directly to anchored sections more predictable. #### Verify both starting and changing states Load the page with reduced motion enabled, then change the preference while the page is open if your environment allows it. Test the manual switch and navigate to another route. Check that loops stop, transforms reset cleanly and controls still announce results. A reduced-motion implementation is complete only when it covers the whole experience. Sources: - [MDN: prefers-reduced-motion](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/prefers-reduced-motion): Reference source. ### Design Subtle CSS Background Patterns Without Competing with Content Canonical URL: https://ourjs.in/blog/css-background-patterns/ Author: Nayan Kumar. Published: 2026-10-26. Category: CSS. Use gradients for grids and stripes, control their visual weight, and keep decorative texture out of the reading path. #### Give the pattern a limited job A faint grid can suggest a technical workspace or give an illustration depth. It should not become the loudest element behind a paragraph. Decide where the texture belongs: perhaps the hero artwork or a project preview, rather than every section. Restricting its scope makes the page’s content hierarchy easier to maintain. #### Build a simple grid from gradients Two perpendicular linear gradients can draw horizontal and vertical rules, with background-size controlling their spacing. For example, a large 48-pixel grid can sit behind a browser illustration. Start with low-opacity lines and a solid base color. You can adjust the rhythm without downloading a raster texture at multiple resolutions. #### Use repeating gradients for regular bands A repeating-linear-gradient continues a set of color stops along a direction, making it useful for stripes or diagonal hatching. Keep stop distances intentional so the pattern remains understandable at the displayed scale. Very fine high-contrast stripes can create visual noise, especially when the page is scaled or captured at a different device pixel ratio. #### Protect text with reliable surfaces If a card contains body text, place that text on a sufficiently solid surface instead of assuming a faint pattern will always remain harmless. Gradients can vary the effective background color across a line of text. Review contrast at the least favorable point and check small labels separately from large display headings. #### Animate the scene, not every pixel A decorative layer can move slightly as part of a composition, but endlessly changing a large pattern’s background position may be unnecessary work. Keep any animation limited and measure it. Provide a static appearance under reduced-motion settings. The visual identity should survive when the texture and its movement are both removed. #### Check the texture in context Inspect the pattern on a phone, a wide desktop and a printed page. Look for interference with thin icon strokes, small captions and focus indicators. Test a screenshot after image compression as well if the page is used in portfolio previews. A good background texture supports the subject quietly instead of becoming an additional subject to decode. Sources: - [MDN: repeating-linear-gradient()](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/gradient/repeating-linear-gradient): Reference source. ### Design TypeScript Props Around Valid Component Usage Canonical URL: https://ourjs.in/blog/typescript-component-props/ Author: Nayan Kumar. Published: 2026-10-26. Category: TypeScript. Write component contracts that explain required data, events and supported variations without boolean overload. #### Start with the caller’s job A useful props type explains how another developer should use a component. It should make required content obvious and prevent combinations the component cannot render meaningfully. Begin with real call sites rather than a long list of imagined future options. A project card that needs a title and destination has a clearer contract than a card that accepts every field optionally. #### Make events describe intent For a quantity picker, an onQuantityChange callback can receive the resulting number rather than exposing an internal button event. That gives the parent the information it needs without coupling it to the implementation. Keep native event types when consumers genuinely need native behavior. The choice should follow the boundary the component represents, not a rule that every callback must look identical. #### Represent distinct modes explicitly Suppose an action can either navigate or submit a form. Separate link and button variants so navigation requires a destination while a button can use a click handler and button type. A discriminating prop can help express the alternatives. Several unrelated booleans such as isLink, isSubmit and isDownload invite conflicting combinations that callers must learn through trial and error. #### Preserve meaningful native capabilities When wrapping a native input, consider which standard attributes callers still need: name, autoComplete, required, disabled and accessible descriptions are common examples. Compose the relevant React attribute types when appropriate, then refine conflicting fields deliberately. Do not accidentally discard an accessibility attribute because the wrapper copied only the props visible in its first mockup. #### Keep optional defaults predictable An optional visual variant can have a simple documented default, while essential information should remain required. Avoid type assertions that silence a missing field only to crash later in rendering. If a value arrives from an external API, validate it before treating it as the component’s trusted props. A compile-time type annotation cannot establish the runtime shape of remote data. #### Review representative call sites Write a minimal valid usage, a fully configured usage and several invalid examples. Check that the invalid combinations are rejected without making common usage cumbersome. Render long text, missing optional imagery, disabled actions and keyboard focus. The type is successful when it guides callers toward a useful interface while leaving the component’s real HTML behavior intact. Sources: - [React: using TypeScript](https://react.dev/learn/typescript): Reference source. ### Encode Unicode Text as Base64 Without Corrupting Characters Canonical URL: https://ourjs.in/blog/unicode-base64-text/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Separate text, UTF-8 bytes and Base64 representation when handling emoji and multilingual content. #### Distinguish text from bytes A JavaScript string is text represented through UTF-16 code units, while Base64 encodes bytes. Confusing those layers often works for simple English and fails for other writing systems. The reliable workflow is to choose a byte encoding for the text, produce those bytes, and then encode the byte sequence. Reverse the same steps when decoding. #### Use an original multilingual example Try a phrase containing an accented name, a Hindi greeting and an emoji in one input. Passing that text directly to btoa can fail because its expected input represents single-byte values. Encode the string with TextEncoder to obtain UTF-8 bytes first. The resulting Base64 should describe those bytes, independent of how the original text looked on screen. #### Keep byte conversion bounded A simple implementation can convert a modest Uint8Array into a binary string before calling btoa. For large content, avoid spreading an enormous array into a function call: argument limits and memory pressure can become a problem. Work in bounded chunks or use an appropriate supported byte-oriented API, and define a realistic input limit for an interactive text tool. #### Decode with a clear failure policy After atob returns byte-valued characters, create a byte array and decode it as UTF-8. A strict TextDecoder can reject invalid sequences rather than silently replacing them. That is useful when the tool promises a text round-trip. If the input actually represents an image or another binary file, a text decoder is the wrong final step. #### Do not confuse representation with secrecy Base64 is reversible encoding, so it does not protect a password or access token. Standard Base64 and URL-safe variants also use different alphabet conventions; accept or normalize a variant deliberately instead of changing characters unpredictably. Explain the accepted input format next to the control so an error is actionable rather than surprising. #### Verify exact round-trips Encode and decode the same multilingual sample, then compare the complete strings rather than only their visual appearance. Include line breaks, combining marks, empty text and a deliberately malformed Base64 value. Check how the UI reports invalid UTF-8 bytes. If interoperability matters, compare the UTF-8 bytes with the system that will receive the value, not just with another browser display. Sources: - [MDN: Window.btoa](https://developer.mozilla.org/en-US/docs/Web/API/Window/btoa): Reference source. ### Export Canvas Images with the Right Format and Dimensions Canonical URL: https://ourjs.in/blog/canvas-image-export/ Author: Nayan Kumar. Published: 2026-10-26. Category: Browser APIs. Handle image decoding, transparency, output MIME types and browser limits in a reliable canvas export. #### Define the output before drawing An image export needs explicit pixel dimensions, format and transparency behavior. CSS dimensions on a canvas affect its display size, while the canvas width and height properties define the bitmap being exported. Set the bitmap dimensions before drawing. Changing those properties afterward clears the drawing surface, which can produce an empty output even though the preview looked correct earlier. #### Walk through a thumbnail example Suppose a 1600 by 1200 photograph needs an 800 by 600 thumbnail. Decode the source, create an 800 by 600 canvas and draw the image into that rectangle. Those dimensions preserve its proportions. Entering 800 by 800 would stretch the image unless the application implements an intentional crop. Explain whether the tool resizes, contains or crops instead of leaving the visitor to guess. #### Choose transparency behavior deliberately PNG supports lossless pixel storage and transparency. JPEG does not preserve an alpha channel, so fill a chosen background before drawing transparent source content into a JPEG export. A white background is a common useful choice, but it should be documented. A logo that looks fine on a dark preview can otherwise become unexpectedly different in its downloaded version. #### Check the actual encoded result toBlob can receive a preferred MIME type and quality value for supported lossy encoders. Unsupported requested formats can fall back to PNG, and the callback can receive null when output creation fails. Inspect the Blob type before assigning the extension. A file named photo.webp containing PNG bytes creates avoidable confusion for later processing and asset delivery. #### Respect decoding and security limits Large bitmaps consume memory beyond their compressed file size. Release decoded resources when practical and reject unreasonable dimensions before allocating an enormous canvas. Drawing certain cross-origin content can also make a canvas unavailable for export. Local file selection and correctly configured remote image delivery need different handling; a client-side exception should produce a useful explanation rather than an endless spinner. #### Verify the downloaded artifact Download a known transparent sample and a photograph, then inspect the actual dimensions and format with another viewer. Compare quality at realistic display size, not only a small preview. Try invalid files and unsupported output behavior. Keep originals available because conversion can discard metadata or animation, and an export that succeeds technically may still be unsuitable for the visitor’s intended use. Sources: - [MDN: HTMLCanvasElement.toBlob](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob): Reference source. ### Find the LCP Bottleneck Before Compressing the Hero Again Canonical URL: https://ourjs.in/blog/measure-lcp-bottlenecks/ Author: Nayan Kumar. Published: 2026-10-26. Category: Performance. Separate response delay, resource discovery, download time and rendering work when investigating Largest Contentful Paint. #### Identify the measured element Largest Contentful Paint reports when the largest eligible visible image or text block is rendered during the relevant loading window. Begin by identifying the element in the actual measurement. It may be a headline on one viewport and a photograph on another. Optimizing an unrelated logo because it appears near the top of the page can miss the real bottleneck. #### Break the delay into stages A late result can come from a slow document response, delayed discovery of the resource, a long transfer, or work that prevents rendering after the bytes arrive. Inspect the network waterfall and performance trace rather than attributing the entire time to image size. Each stage suggests a different change, and improvements in one stage can expose a new limiting factor elsewhere. #### Use a practical discovery example Suppose a hero image URL is only inserted after a large JavaScript bundle runs and an API request completes. Reducing that image’s file size helps transfer time but does not eliminate the preceding discovery delay. Where the design permits it, render the important image reference in the initial markup so the browser can begin its work earlier. #### Consider text and rendering dependencies When the measured element is text, investigate styles, font delivery and main-thread work that delays its appearance. A decorative intro that keeps the headline invisible until a timeline ends can make the experience feel slow despite a fast network. Keep meaningful content available promptly and treat motion as an enhancement around it rather than a requirement for reading. #### Prioritize with comparable evidence Measure the same route, viewport and approximate conditions before and after a change. Use several runs for lab comparisons and field data when available to understand real visits. Avoid reporting a single unusually fast run as a universal improvement. Record the element and the stage you intended to improve so the result can be interpreted instead of reduced to an unexplained score. #### Verify the visitor’s experience After an optimization, check visual quality, responsiveness and layout stability. A tiny blurry hero or a broken fallback is not a good result merely because a timing metric falls. Confirm the main content appears usefully on slower mobile conditions. Keep a short record of the bottleneck, change and observed outcome so future design additions do not silently recreate the same delay. Sources: - [web.dev: optimize Largest Contentful Paint](https://web.dev/articles/optimize-lcp): Reference source. ### Flexbox Wrapping for Toolbars, Tags and Button Groups Canonical URL: https://ourjs.in/blog/flexbox-wrapping-layouts/ Author: Nayan Kumar. Published: 2026-10-26. Category: CSS. Use flexible wrapping to keep everyday interface groups usable when labels grow or space gets tight. #### Recognize a one-dimensional group A row of filter buttons, project tags or social links is often a good fit for Flexbox. The items belong in a sequence that can continue onto another line. Start with their natural reading order in the HTML. Reordering them visually to fit a particular screenshot can make keyboard movement feel disconnected from the arrangement. #### Enable wrapping deliberately A flex container does not wrap by default. Add flex-wrap:wrap when items should move to a new line instead of being squeezed or overflowing. Combine it with a gap for consistent spacing. In a filter bar, this lets longer labels stay intact while the group takes the vertical space it actually needs. #### Decide which items may grow A search field can flex to use remaining space, while a compact category button may keep its natural size. For example, give a search wrapper flex:1 1 14rem and keep its input at width:100%. This communicates both a preferred size and the permission to shrink or move when the toolbar becomes narrow. #### Treat each line as independent Wrapped Flexbox lines distribute space separately. A row containing four tags does not guarantee the same column alignment as the next row containing two. That is often ideal for chips and action groups. If precise alignment across both rows and columns is the requirement, Grid may be the better layout model. #### Protect labels and focus indicators Avoid fixing a button’s height so tightly that a translated or zoomed label is clipped. Allow a reasonable minimum size and line height. Make sure row gaps leave room for focus outlines around adjacent controls. A tightly packed toolbar can technically wrap and still feel difficult to operate because its interactive boundaries are unclear. #### Try realistic variations Test the longest filter name, a search field with text entered, a disabled action and a browser zoom level that makes the group wrap. At a very small width, a single-column arrangement may be clearer than elaborate space distribution. Judge success by whether each control remains understandable and reachable, not whether every row has the same number of items. Sources: - [MDN: flex-wrap](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/flex-wrap): Reference source. ### Fluid Typography with Clamp: Scale Headings Without Losing Control Canonical URL: https://ourjs.in/blog/fluid-type-clamp/ Author: Nayan Kumar. Published: 2026-10-26. Category: CSS. Combine minimum, preferred and maximum font sizes while keeping long headings and text resizing usable. #### Set the reading constraints first A large portfolio heading needs to remain legible on a small screen and restrained on a wide one. Decide the smallest acceptable size and the largest useful size before choosing a scaling formula. Those boundaries should follow the actual heading and available line length, rather than copying values from a visually different landing page. #### Read the three parts of clamp A declaration such as font-size:clamp(2.25rem, 1.25rem + 4vw, 5rem) has a lower bound, a preferred expression and an upper bound. The middle expression responds to viewport width, while the bounds stop it becoming too small or too large. Keep compatible units and spacing around arithmetic operators when writing the expression. #### Include a relative text component Using only viewport units can make text resizing behave in surprising ways. A preferred value that includes rem ties part of the result to the root font size. That is not a guarantee of accessibility by itself. Test browser zoom and user font settings to confirm the heading can actually enlarge without clipping or overlapping other content. #### Design the line breaks as content A heading like Interfaces that work beautifully may occupy two lines at one width and three at another. Give it an appropriate maximum line length and line height. Avoid inserting a forced line break after every word simply to imitate the desktop composition. A fluid font size cannot rescue a rigid block that refuses to accommodate real text. #### Use a small hierarchy of scales Not every label needs fluid sizing. Reserve the larger scaling range for display headings, use a modest range for section titles, and keep body text comfortably readable. A site with every caption changing size can feel unsettled. Consistent spacing and predictable hierarchy usually matter more than making every value respond continuously. #### Verify the endpoints and the middle Inspect the heading at the minimum width, the maximum width and several widths in between. Replace it with a longer project title and increase the browser’s text size. Check buttons, navigation and adjacent imagery for collisions. Keep a simple fallback font size if supporting environments that do not understand the chosen modern CSS expression. Sources: - [MDN: clamp()](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/clamp): Reference source. ### Focus-Visible Styling That Fits Your Design and Remains Obvious Canonical URL: https://ourjs.in/blog/focus-visible-styling/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Give keyboard focus a consistent visual language across links, buttons, cards and form controls. #### Treat focus as a designed state Focus identifies the element that will receive the next keyboard action. It deserves the same attention as hover and active states. A portfolio may contain large clickable cards, small social links and text inputs; each needs a clear indicator. Removing the browser outline without a replacement makes the interface harder to navigate. #### Use focus-visible for the right distinction The :focus-visible pseudo-class follows the browser’s decision about when a focus indication is needed. It is useful for providing a deliberate keyboard indicator without making every pointer click look the same. Do not assume it simply means Tab was pressed. Input methods and element types affect the browser’s behavior, so test the controls themselves. #### Give the indicator separation An outline with an offset can remain distinct from the component’s border. For example, a plum outline around a silver card may be clearer when separated by a few pixels. Avoid relying only on a subtle background tint, especially when the unfocused card already has a gradient or a hover spotlight effect. #### Handle conflicting surfaces One ring color may disappear when a component moves from a light panel to a dark one. Theme the focus color or use a layered treatment that remains visible across the supported backgrounds. Check the outline against both the control and the surrounding surface. Consistency means a recognizable pattern, not necessarily an identical hexadecimal value everywhere. #### Prevent clipping and movement Overflow-hidden wrappers can cut off a focus ring placed outside a card. Give the wrapper enough room or apply the indicator to a visible boundary. Hover lift effects also need consideration: a focused card should not jump away from the reader or overlap the next row. Keep the focused location stable enough to follow. #### Walk the finished interface Press Tab through the header, project cards, article links, form fields and footer. Repeat with browser zoom and in the mobile menu. Confirm that focus remains visible when a sticky header or floating panel is present. Keep a sensible :focus fallback for environments outside your support assumptions instead of using a global outline:none rule. Sources: - [MDN: :focus-visible](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/:focus-visible): Reference source. ### Format Dates Without Accidentally Changing the Day Canonical URL: https://ourjs.in/blog/date-timezone-formatting/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Distinguish calendar dates from instants and make locale and time-zone decisions explicit. #### Identify the kind of date you have A birthday, an article publication day and an exact event timestamp are different kinds of information. A calendar date does not necessarily describe midnight in someone’s time zone. An instant describes a point on a shared timeline that can be displayed in different zones. Decide which meaning the field has before converting it into a JavaScript Date. #### Make a concrete publication example Suppose an article is labeled 2026-10-26 and should display that same calendar day everywhere. Parsing it as an instant and formatting it in a time zone behind UTC can show the previous day. Preserve the date-only meaning, or use an explicit formatting convention that does not accidentally shift it. Keep that policy consistent in both the page and structured metadata. #### Choose locale and time zone intentionally Intl.DateTimeFormat separates locale-sensitive presentation from the underlying timestamp. For a scheduled event, specify the intended IANA time zone when the event location matters. For a personal activity feed, the viewer’s local zone may be the desired presentation. Include a visible zone label where ambiguity could cause someone to arrive or act at the wrong time. #### Validate input before formatting Check that a timestamp is valid before displaying it. Also define whether numeric timestamps use seconds or milliseconds, because mixing those units can produce a plausible-looking but entirely wrong date. Avoid loosely parsed human-readable strings as an interchange format. Prefer a documented ISO representation with a zone or offset when communicating an instant across systems. #### Avoid server-client presentation mismatches A server and browser may use different default locales or time zones. If both independently format the same value without explicit options, their text can differ. For stable public content, render a deterministic date string. For viewer-local presentation, keep the initial rendering strategy deliberate and consider how the text changes after the browser knows the viewer’s environment. #### Check the awkward boundaries Test midnight-adjacent instants, a date-only value, an invalid input and at least two time zones on opposite sides of UTC. Include a region with daylight-saving transitions when scheduling is involved. Compare visible text, the time element’s dateTime value and exported data. These should communicate compatible meanings, rather than simply containing strings that happen to look like dates. Sources: - [MDN: Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat): Reference source. ### Generate Browser Random Values Without Modulo Bias Canonical URL: https://ourjs.in/blog/crypto-random-values/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Use Web Crypto carefully when mapping random bytes to password characters and other finite choices. #### Choose randomness for the actual requirement A decorative animation can use ordinary pseudo-random variation without promising security. A password generator needs a different standard and should use the browser’s cryptographic facilities. Be explicit about that distinction in implementation and interface copy. Calling something random does not explain its source, distribution or suitability for the operation the visitor intends to perform. #### Fill an integer typed array crypto.getRandomValues writes values into an integer typed array supplied by the caller. For a modest password operation, a small Uint8Array provides a convenient batch of random byte values. Keep allocations proportionate to the requested output. The API has a per-call byte limit, so generating a very large payload requires deliberate chunking rather than one enormous request. #### See the bias in a small example A byte has 256 possible values. If an alphabet has ten characters, mapping every byte with value modulo ten gives some characters more possible byte inputs than others. Reject bytes at or above 250, then map the remaining bytes modulo ten. Every retained character now has the same number of byte inputs, making the selection rule easier to reason about. #### Generalize with rejection sampling For an alphabet of length n that fits the byte range, calculate the largest multiple of n no greater than 256 and reject values beyond that boundary. Continue drawing until the required output length is reached. This addresses distribution bias in the mapping step; it does not by itself establish a complete password policy or guarantee every character category appears in a result. #### Keep promises limited and useful Explain the selected alphabet, length range and local processing behavior. Do not call Base64 encoding encryption or imply that a generated value can be recovered after closing the page. Clipboard history, screen sharing and browser extensions are separate considerations from randomness. For actual cryptographic key creation, use the appropriate key-generation API and a reviewed protocol rather than repurposing a password helper. #### Verify constraints rather than predicting output Check requested lengths, permitted characters and error handling when an API is unavailable. Exercise the rejection boundary with controlled test values in a small isolated mapping function. Do not expect a single short output to include every character type. Review the interface so that copying, regeneration and replacing an old result are clear without logging generated secrets into diagnostics. Sources: - [MDN: Crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues): Reference source. ### Generate Next.js Route Metadata from the Same Record as the Page Canonical URL: https://ourjs.in/blog/nextjs-route-metadata/ Author: Nayan Kumar. Published: 2026-10-26. Category: Next.js. Prevent title, canonical and social-card mismatches when one route template renders many public pages. #### Share facts rather than copy A content record already knows an article’s title, description and slug. Use that record for both the visible page and its metadata. Maintaining a second title map invites drift when an editor renames a guide. The goal is a single reliable source for factual fields, while allowing the visible headline and preview copy to have intentional editorial differences. #### Choose the appropriate metadata export Static page information can use a metadata object, while route-dependent information can use generateMetadata. These APIs belong on the server side in the App Router. Keep a stateful editor or search component in a child Client Component instead of moving the page boundary and then attempting to export unsupported metadata from it. #### Build a small route example Suppose /tools/[slug]/ looks up the color-converter record. The route can construct its title, description, canonical and Open Graph URL from that record and the production origin. If no record matches, use the missing-page path consistently. Do not return metadata for a generic tool while the body renders an error or an unrelated fallback. #### Inspect inherited nested fields A title template is helpful for a short identity suffix, but inherited objects need deliberate handling. Ensure a page’s social title and URL actually describe that page instead of leaving the homepage values in place. Resolve relative URLs against the intended metadata base, and confirm that a preview environment has not become the canonical production origin. #### Keep metadata accurate at build time For static output, the generated records must be available when the build runs. An asynchronous lookup does not automatically require request-time behavior, but a private live dependency can still fail or make a build nondeterministic. Validate required fields before rendering so missing descriptions or malformed dates become actionable content errors rather than silently inconsistent head tags. #### Audit generated HTML as a set Inspect several routes manually, then extract titles and canonical URLs across the export. Check uniqueness, expected destinations and social metadata correspondence. Include articles with long names and missing slugs in the sample. A helper function is only a convention; the final HTML is the artifact that reveals whether templates, inheritance and route data produced the result you intended. Sources: - [Next.js: generateMetadata](https://nextjs.org/docs/app/api-reference/functions/generate-metadata): Reference source. ### Improve Interaction Responsiveness by Finding the Work Around a Click Canonical URL: https://ourjs.in/blog/reduce-inp-long-tasks/ Author: Nayan Kumar. Published: 2026-10-26. Category: Performance. Investigate input delay, event-handler work and rendering cost instead of assuming every slow interaction is a React rerender. #### Measure a real interaction Interaction to Next Paint concerns how promptly a page responds visually to interactions over a visit. Start with an interaction a person can reproduce: opening a menu, typing in a filter or processing a file. Record what was happening before the interaction as well as inside its handler, because unrelated main-thread work can delay the event before your code begins. #### Separate the sources of delay An interaction can wait for existing work, spend time executing its handlers, and then wait for the browser to produce the next frame. A short handler does not prove the experience is responsive. Inspect the performance trace for long tasks, expensive style calculations and layout work, then connect those observations to the specific interaction rather than guessing from component count. #### Use a tool-directory example Imagine a search box that filters hundreds of large card components on every keystroke while also recalculating expensive article summaries. Precompute stable searchable text and avoid repeating unrelated calculations in the input path. If work remains substantial, consider how it can be deferred or divided. Do not debounce essential input feedback so aggressively that the control appears to ignore the user. #### Move suitable work off the critical path Heavy independent computation may fit a worker, while large sequential loops may need chunking and yielding. Keep each approach’s data-transfer and coordination cost in mind. A worker does not remove the cost of drawing a huge DOM, and a loading spinner cannot render while synchronous JavaScript monopolizes the same main thread. Choose the technique that addresses the observed work. #### Control decorative overhead Pointer effects and scroll animations can compete with useful interactions if they perform repeated layout reads, trigger expensive paints or update many components unnecessarily. Batch event-driven work, avoid continuous loops when nothing changes, and respect motion preferences. Test with realistic low-end conditions because a desktop workstation can conceal contention that becomes obvious on a phone. #### Verify feedback and completion separately A control should acknowledge an action promptly and eventually finish the requested task correctly. Measure both without assuming that immediate feedback makes long processing disappear. Repeat the interaction during loading and after the page settles, and consult field data when available. Keep the result tied to a specific behavior so later changes can be checked against the same reproducible scenario. Sources: - [web.dev: optimize Interaction to Next Paint](https://web.dev/articles/optimize-inp): Reference source. ### Invalidate CDN Content Deliberately Instead of Purging Every Release Canonical URL: https://ourjs.in/blog/cdn-cache-invalidation/ Author: Nayan Kumar. Published: 2026-10-26. Category: DevOps. Choose versioned URLs, targeted invalidations and verification steps based on the content that actually changed. #### Identify what must change immediately A CDN keeps reusable responses near visitors. When a published file changes before its cached representation expires, decide whether the update needs a new URL, an invalidation, or ordinary expiration. These are operational choices with different consequences. Start from the changed resource and its references rather than making a blanket cache purge the first step of every deployment. #### Prefer stable versioning for assets Versioned CSS, JavaScript and image filenames let new documents point to new content while old files remain valid for existing sessions. This approach avoids waiting for a previous URL to expire. It is different from storage-level object versioning, which can preserve historical objects without automatically changing the public URL requested by a browser. #### Use a targeted correction example Imagine a public HTML page incorrectly displays an old project title while all versioned assets are correct. Publishing corrected HTML and invalidating the affected document path is more focused than clearing every image and script. Verify whether both a directory URL and an index-file URL are exposed by the host, because cache entries follow requested paths and configuration. #### Account for layers beyond the CDN An invalidation affects the CDN’s stored content; it does not necessarily erase a browser’s local copy or an independent corporate proxy cache. If the same public filename is reused with long browser caching, visitors can remain on an old representation after the CDN is refreshed. Fix the URL and header policy that created the problem rather than assuming the purge reaches every cache. #### Treat invalidation as a deployment step Track the requested paths, release identifier and completion state. Avoid declaring success immediately after submitting a request if propagation is still in progress. Coordinate invalidation with origin updates so the next cache miss retrieves the intended version. Purging first and uploading later can refill the edge with the same stale content you were trying to replace. #### Verify with a known marker Fetch the updated resource through the public delivery path and compare a harmless release marker or expected content. Check the browser request as well as an origin inspection when debugging. Keep the previous release available and document why each invalidation was needed. Over time, frequent broad purges are a signal to review versioning and cache policies, not simply to automate a larger purge. Sources: - [AWS: invalidate CloudFront files](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html): Reference source. ### JSON Parsing Is Only the First Step of Validation Canonical URL: https://ourjs.in/blog/json-parse-validation/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Separate valid JSON syntax from a safe, useful application data shape at import and API boundaries. #### Separate syntax from meaning JSON.parse answers whether a string can be interpreted as JSON and returns the resulting JavaScript value. It does not answer whether that value matches your feature’s expectations. A string, null or array may be perfectly valid JSON while being unusable as a settings record. Write down the required data shape before treating parsing as successful import. #### Build a small import contract For a theme import, suppose the accepted object needs a nonempty name and a colors array of six-digit HEX strings. Parse the text inside try and catch, then check that the result is a non-null object rather than an array. Validate each required property and array entry separately. Only copy the allowed fields into the internal settings value. #### Keep diagnostics specific A syntax error should explain that the JSON could not be parsed. A shape error should identify the relevant field, such as colors must contain only supported HEX strings. Avoid replacing every failure with Invalid data when the user could easily fix the problem. Keep the original pasted text available so correcting one issue does not require reconstructing the entire import. #### Watch number and duplicate-key behavior JSON numbers become JavaScript numbers in an ordinary parse, which can lose precision for large integers. If exact external identifiers matter, transport them as strings. Also decide how your import policy treats duplicate object keys; a parsed object alone may not preserve evidence of those duplicates. A dedicated parser may be needed when detecting them is part of the contract. #### Do not turn parsed data into executable content Never use eval as a JSON parser. Do not insert imported strings as unrestricted HTML or merge arbitrary external properties into privileged configuration objects. Parsing is not sanitization, authorization or proof that an API response is trustworthy. Keep those boundaries explicit, and validate again on the server for operations whose rules must be enforced centrally. #### Verify a useful rejection matrix Test malformed JSON, null, an array, a missing name, an empty colors list and one invalid color. Include an unusually large input to check responsiveness and an integer outside the safe range. Confirm that a valid import produces a new reviewed value without silently changing unrelated settings. Good validation preserves user control while refusing data the feature cannot interpret reliably. Sources: - [MDN: JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse): Reference source. ### Keep Anchor Headings Visible Beneath a Sticky Header Canonical URL: https://ourjs.in/blog/sticky-header-anchor-offset/ Author: Nayan Kumar. Published: 2026-10-26. Category: CSS. Use scroll offsets and reliable target ids so table-of-contents links land where readers expect. #### Reproduce the hidden heading Open an article and activate a table-of-contents link. If the target heading aligns with the top of the viewport while a sticky header occupies the same area, the heading disappears behind it. This is easy to overlook during ordinary scrolling because the content may look correct until someone uses fragment navigation. #### Choose the right offset location Scroll-margin-top on a target can provide space when that target is scrolled into view. Scroll-padding-top on a scroll container expresses an inset for that container’s scrollport. Choose the approach that matches the layout and supported navigation behavior. Avoid combining several arbitrary offsets without checking their combined effect on the actual page. #### Use a measured design value If the header is 72 pixels tall, an offset slightly larger than that can give the heading useful breathing room. Store the header dimension in a custom property if multiple rules share it. Revisit the value when the header changes at a breakpoint. A desktop-only assumption can hide headings on a phone with a taller menu row. #### Keep ids stable and unique Generate fragment ids from meaningful headings, but account for duplicates and punctuation. Two sections both named Results need distinct identifiers. Links copied from a table of contents should continue to reach the same section after an unrelated design change. Avoid using array positions as public fragment ids if sections may be reordered later. #### Do not require smooth scrolling Smooth movement is optional; reaching the correct content is the essential behavior. Respect reduced-motion preferences and allow an immediate jump when appropriate. A custom click handler should not break opening a fragment in a new tab or copying its URL. Ordinary links already supply useful browser behavior that a decorative scrolling effect can accidentally remove. #### Verify entry from outside the page Test the table of contents, a copied URL containing the fragment, browser back navigation and keyboard activation. Confirm the heading is readable after the destination loads and after images above it finish loading. Then test the skip link separately. Both interactions need a sensible landing point, even if they use different target elements. Sources: - [MDN: scroll-margin-top](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/scroll-margin-top): Reference source. ### Keep Large Identifiers Safe in JavaScript Canonical URL: https://ourjs.in/blog/javascript-safe-integers/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Recognize numeric precision limits and preserve identifiers through JSON, forms and table exports. #### Decide whether the value is really a number An account identifier may contain only digits while still being a label rather than a quantity. If nobody should add or multiply it, a string is often a better contract. That choice also preserves leading zeros and avoids numeric formatting surprises. Choose the representation at the API boundary instead of trying to repair precision after a table already contains rounded values. #### Understand the safe-integer boundary Ordinary JavaScript numbers use floating-point representation. Integer values are considered safe only within the range from negative 9,007,199,254,740,991 to positive 9,007,199,254,740,991. Number.isSafeInteger checks both the integer requirement and that range. Being a finite number or an integer does not by itself prove that neighboring large integers can still be distinguished reliably. #### Follow an identifier through a workflow Imagine a CSV import with a record identifier longer than sixteen digits. Keep the field as text when parsing, editing, filtering and exporting it. Do not convert it with Number merely because a form input looks numeric. A search for that identifier must compare its exact string representation, otherwise two distinct external records could appear to refer to the same row. #### Use BigInt when arithmetic is required BigInt can represent integer quantities beyond the safe Number range, but it has different interoperability rules. Do not casually mix it with Number arithmetic. Decide how it travels across JSON and database boundaries, usually through an explicit string representation and conversion rule. It also does not solve arbitrary decimal arithmetic, which requires a separate representation and rounding policy. #### Validate before losing information Checking Number.isSafeInteger after a value has already been rounded cannot recover the original digits. Validate the source string and preserve it until the correct conversion is known. A JSON producer can send an identifier as a quoted string rather than an oversized numeric literal. Document this contract so a future backend or export change does not silently reintroduce the issue. #### Verify neighboring and formatted inputs Test leading zeros, the safe-range boundary, a value beyond it and two large neighboring identifiers. Check form submission, JSON round-trips and spreadsheet export separately. Confirm that the displayed text exactly matches the source and that sorting uses the intended rule. A correct first screen is insufficient if a later download changes the identifier that another system depends on. Sources: - [MDN: Number.isSafeInteger](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger): Reference source. ### Keep Multiple Frontend Instances on a Coherent Release Canonical URL: https://ourjs.in/blog/consistent-multi-instance-releases/ Author: Nayan Kumar. Published: 2026-10-26. Category: DevOps. Use immutable artifacts, release identifiers and compatibility windows to prevent intermittent mixed-version behavior. #### Recognize the mixed-release symptom A page that alternates between old and new interfaces across requests may be reaching different application instances or cache entries. Treat that as a version-consistency question before blaming the browser. Capture response identifiers and requested asset names on both successful and incorrect views. Without that evidence, repeated reloads can obscure which part of the delivery system is inconsistent. #### Promote one artifact Build a release once, identify it by commit or artifact digest, and promote that same output through the intended environments. Rebuilding independently on each server creates opportunities for differences in dependencies, configuration and generated content. An artifact should have a traceable relationship to the source and checks that produced it, regardless of where it is finally served. #### Plan a realistic rollout example Suppose two frontend instances serve release A while release B is introduced. During the transition, an older HTML document may still request A’s assets. Keep those assets available and ensure shared services tolerate the planned overlap. A deployment is not coherent merely because each individual instance starts successfully; visitors can cross boundaries during a normal session. #### Separate code and configuration Record which settings were built into client files and which are read at runtime. A static browser bundle does not acquire new build-time values because it moved to a different server. Conversely, runtime API settings can differ across instances even when code matches. Include these distinctions in the release inventory so configuration drift is not mistaken for an unexplained code regression. #### Control concurrent publications Two deployment jobs writing to the same destination can interleave files or publish an older commit after a newer one. Use the platform’s deployment coordination mechanisms and choose cancellation behavior deliberately. For static files, prefer a complete release directory and controlled switch over many uncontrolled overwrites of the live document root where the hosting system supports that approach. #### Verify across the serving path Check release markers through the load balancer and relevant regions, inspect deep routes, and test client navigation after rollout. Monitor missing asset responses and runtime errors for evidence of incompatible versions. Keep rollback instructions tied to complete artifacts. A repair that restores HTML but leaves mismatched scripts or environment settings can preserve the same mixed-release failure under a different name. Sources: - [GitHub: workflow concurrency](https://docs.github.com/en/actions/concepts/workflows-and-actions/concurrency): Reference source. - [AWS: versioned delivery paths](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/UpdatingExistingObjects.html): Reference source. ### Keep Useful Content Crawlable in a JavaScript-Enhanced Website Canonical URL: https://ourjs.in/blog/crawlable-javascript-content/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Separate the information a visitor needs from the JavaScript that powers filters, animations and interactive tools. #### Separate content from enhancement A page can be interactive without making all information depend on client-side execution. Keep its purpose, instructions, headings and navigation in the initial HTML where practical. Use JavaScript for the actions that need it, such as processing an image or filtering a list. This boundary helps visitors understand the page even if an enhancement is delayed. #### Inspect two representations Read the server response and then inspect the hydrated page. A script-generated result is not inherently invisible to search, but rendering introduces dependencies on resources and execution. Compare the representations to identify missing titles, a loading placeholder that never resolves, or links that exist only after a user interaction. Record the specific difference instead of assuming all JavaScript is a problem. #### Use a tool page example A JSON formatter can ship its name, explanation, examples and related guides as static HTML, then attach the editor controls in the browser. The actual formatted result only exists after someone supplies input and does not need to be indexed. Searchable explanation and personal tool output are different kinds of content, so they deserve different rendering decisions. #### Avoid hiding content behind motion Animations should enhance the layout rather than act as a gate to reading it. If a reveal observer never starts, the text should remain visible. Reserve space for illustrative scenes and provide reduced-motion behavior. Do not place the only meaningful description inside a canvas illustration that has no equivalent readable explanation on the page. #### Keep routes and resources honest Give important pages stable URLs and ordinary navigation links. Return the appropriate status for missing pages rather than serving the same successful application shell for every path. Review robots rules for required scripts and styles, and make sure public content does not depend on a logged-in API that a crawler cannot access. #### Verify on the published site Test a direct navigation to a detail URL, not only a transition from the homepage. Inspect the response, disable a nonessential enhancement, and check that the main purpose remains understandable. After deployment, search inspection tools can show rendered HTML from the search system’s perspective. Your own browser test and a crawler’s observed rendering are related evidence, not interchangeable guarantees. Sources: - [Google: JavaScript SEO basics](https://developers.google.com/search/docs/crawling-indexing/javascript/javascript-seo-basics): Reference source. ### Keyboard-Friendly Navigation for a Personal Portfolio Canonical URL: https://ourjs.in/blog/keyboard-friendly-navigation/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Make the journey through menus, cards and contact controls work with Tab, Enter and a visible focus indicator. #### Test without a pointer Put the mouse aside and open the homepage with a keyboard. Press Tab from the address bar and record the first few stops. The sequence should lead through useful controls in a predictable order. If the focus disappears, jumps into a hidden menu or reaches decorative artwork, there is a concrete navigation problem to fix. #### Prefer native controls A real link with an href supports navigation, while a button supports an action such as opening a menu. These elements bring familiar keyboard behavior. A clickable div requires extra work for focus, roles, keys and disabled states, and it is easy to implement only the click handler while leaving the keyboard interaction incomplete. #### Keep the order in the document Let the natural DOM order define the tab sequence. Positive tabindex values create a second ordering system that becomes fragile as the page changes. If a sidebar looks right but is reached at an unexpected point, inspect the source order and layout rules before trying to repair the experience by numbering focusable elements. #### Design visible focus states A focused control needs an indicator that works against its actual background. On a silver card, a plum outline can be more legible than a pale shadow. Give the outline breathing room and make sure overflow clipping does not cut it off. Hover styling alone cannot communicate where a keyboard user currently is. #### Explain expanded navigation For a mobile disclosure menu, keep the toggle button’s expanded state synchronized with the visible panel. Hidden links should not remain in the tab order. Escape can dismiss the open menu and return focus to its toggle. A normal navigation disclosure does not need the arrow-key behavior of an application-style menubar. #### Check complete user journeys Follow the route from homepage to project, then to contact, using only the keyboard. Open and close navigation, activate a download and reach the footer. Repeat at narrow widths and with browser zoom. A keyboard check is most useful when it covers an actual task instead of merely counting how many controls can receive focus. Sources: - [MDN: keyboard accessibility](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Guides/Understanding_WCAG/Keyboard): Reference source. ### Know Which Environment Variables Become Part of Your Frontend Build Canonical URL: https://ourjs.in/blog/deployment-environment-variables/ Author: Nayan Kumar. Published: 2026-10-26. Category: DevOps. Separate public configuration, server secrets and build-time values before promoting a browser bundle between environments. #### Classify the value before naming it An environment variable is a way to supply configuration, not a guarantee that its value remains private. Decide whether the value is safe for every visitor to inspect. A public API base URL is different from a privileged API credential. This classification should happen before a developer chooses a framework prefix or adds a value to a build command. #### Understand build-time substitution In Next.js, supported NEXT_PUBLIC_ references are inlined into browser code at build time. Changing a host’s environment after the artifact is built does not rewrite that existing JavaScript. Treat those values as part of the artifact’s inputs and record the intended environment. Otherwise, a production deployment can continue calling the preview service even though the server dashboard shows a new setting. #### Trace a practical configuration error Imagine a bundle built with NEXT_PUBLIC_API_ORIGIN pointing to https://preview.example.com. Promoting those exact files to the production domain preserves that embedded origin. Either build the artifact with the intended public value or design an explicit runtime configuration mechanism appropriate to the hosting model. Do not assume that moving files changes constants already included in them. #### Keep secrets out of client output Do not place privileged tokens in a public variable, metadata object or generated source file. A variable without a public prefix still needs careful handling: code can accidentally serialize its value into HTML or logs. Keep sensitive operations on an appropriate protected backend, and give automation only the credentials required for its actual publishing task. #### Validate configuration early Check required values at the stage where they are needed and produce an error that names the missing setting without printing its contents. Document which variables are public, required, optional or environment-specific. Use example configuration files with harmless placeholder values, and keep real local secrets outside version control. Distinguish a missing setting from an unavailable remote service when reporting failures. #### Inspect the generated artifact Before release, inspect the public network requests and generated files for unexpected origins or exposed credentials. Verify configuration against the deployed site, not only the pipeline’s variable list. If a secret was shipped publicly, removing it in a later build is insufficient because copies may remain cached; follow the relevant credential rotation process. Configuration review belongs beside code review because it changes application behavior. Sources: - [Next.js: environment variables](https://nextjs.org/docs/app/guides/environment-variables): Reference source. - [GitHub: using secrets](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-secrets): Reference source. ### Lazy-Load Below-the-Fold Images Without Delaying the Main Content Canonical URL: https://ourjs.in/blog/lazy-loading-below-fold/ Author: Nayan Kumar. Published: 2026-10-26. Category: Performance. Choose loading priority based on where an image appears and preserve layout space while deferred images arrive. #### Classify images by their role A hero image, an immediately visible project screenshot and a thumbnail far down an archive do not have the same loading needs. Defer images that are not needed for the initial view, while keeping important above-the-fold content discoverable promptly. Adding lazy loading to every image is a mechanical rule that can delay the very content a visitor is waiting to see. #### Use the browser’s built-in behavior For ordinary images, the loading attribute gives the browser a native deferral mechanism. Actual fetching decisions can depend on the browser, connection and distance from the viewport. Treat it as a hint rather than an exact pixel threshold. Prefer the simple built-in approach before introducing a custom observer and placeholder system for a case the browser already handles. #### Reserve the eventual dimensions Provide image dimensions or an appropriate aspect-ratio container so deferred content does not push surrounding text around when it loads. The empty space should reflect the actual intended layout. A placeholder that starts as a short strip and later becomes a tall photograph can still cause movement even though the download was successfully deferred. #### Work through a portfolio example Imagine a project grid that begins beneath the opening introduction. The first visible screenshot may be fetched normally, while later rows use lazy loading. Each screenshot sits inside the same reserved frame. Scroll through the page on a slower connection and check that the headings remain stable and that images arrive before their absence disrupts normal reading. #### Avoid content-discovery traps A deferred image should still have a real source and useful alternative text where appropriate. Do not require a scroll event just to insert the only description of an important project. Custom image effects should leave the content understandable when JavaScript fails or reduced motion is enabled. Loading strategy and decorative animation need separate failure paths. #### Measure the actual improvement Compare initial requests and transferred bytes, then inspect the main content’s loading time and layout stability. Test a direct visit and a deep anchor that opens farther down the page. Confirm that deferral did not break printing or normal navigation for the intended audience. Keep the strategy when it reduces unnecessary early work without making visible content feel late or unstable. Sources: - [web.dev: browser-level image lazy loading](https://web.dev/articles/browser-level-image-lazy-loading): Reference source. ### Maintain an XML Sitemap as a Map of Real Canonical Pages Canonical URL: https://ourjs.in/blog/xml-sitemap-maintenance/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Keep sitemap entries synchronized with published routes, accurate modification dates and your chosen public URLs. #### Generate from the content source A sitemap is easier to trust when it uses the same published records that create the pages. Keep article slugs and tool slugs in a structured collection, then generate the sitemap from those records. A separately maintained URL list tends to retain deleted pages and miss new ones when a collection grows beyond a few entries. #### Include intended indexable destinations List public canonical pages you want discovered, using absolute URLs on the correct production hostname. Remove preview environments, broken links and redirects from the intended set. The file is a discovery aid rather than a command to index everything. A sitemap entry cannot make a thin page useful or override an incompatible access policy. #### Check a small example Imagine a journal with a homepage and three articles. The expected set contains the archive and the three article URLs, along with the other public site pages. Removing one article should update both its route and its sitemap membership. A comparison between the exported HTML routes and sitemap URLs exposes either a missing page or an obsolete entry. #### Use meaningful modification dates If you provide lastmod, derive it from substantive content updates rather than assigning the current deployment time to every URL. Rebuilding an unchanged site does not mean each article was revised. Keep publication and modification dates distinct in the content model so an editor can explain why a timestamp changed and what the reader gained. #### Keep discovery connected Reference the sitemap from robots.txt and submit it through the appropriate search management tools when the site is live. Still provide ordinary links between archives and detail pages. A site whose only path to its articles is an XML file misses an opportunity to help real visitors navigate related subjects and understand the collection. #### Validate structure and coverage Open the final XML, check escaping, and confirm every listed URL resolves as intended. Test that the sitemap itself returns a successful response instead of the site’s generic error page. For larger collections, respect the documented file limits and introduce sitemap indexes when needed. Review reported errors alongside your own route inventory rather than treating submission as the end of maintenance. Sources: - [Google: build and submit a sitemap](https://developers.google.com/search/docs/crawling-indexing/sitemaps/build-sitemap): Reference source. ### Make a Large Article Archive Easy to Browse and Crawl Canonical URL: https://ourjs.in/blog/pagination-crawlable-archives/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Combine stable archive URLs, useful page titles and ordinary navigation with optional search and load-more controls. #### Give each slice an address A growing journal needs a way to reach entries beyond the first screen. Distinct archive pages with stable URLs make those slices shareable and directly accessible. The address should load the same intended set without requiring someone to repeat previous clicks. A client-side filter can improve browsing, but it should not be the only route to older articles. #### Keep navigation available as links Render next, previous and numbered destinations as anchors with meaningful href values. A crawler or keyboard user should not need to activate an opaque load-more button to discover every entry. If the interface adds infinite scrolling, retain an underlying paginated structure so the enhanced experience has an ordinary navigation path beneath it. #### Choose sensible archive semantics Use a clear title and heading for the collection, and identify subsequent pages when appropriate. Each distinct page generally needs its own canonical rather than pointing every slice at the first page. The shared layout does not make different article lists duplicates. Keep the site’s URL convention consistent so links and metadata agree about trailing slashes and hostnames. #### Model a concrete collection For a hypothetical archive of 103 guides, a page size of 12 creates nine archive pages. The final page contains seven entries, not a broken empty layout. Check the transition from page eight to nine, then back to eight. Also test a requested page number beyond the final page and return an appropriate missing-page response. #### Avoid artificial index expansion Every combination of keyword search, category, sort order and page number does not automatically deserve an indexable URL. Decide which archive pages provide a useful destination and which are temporary interface state. An unlimited filter space can create many near-duplicates without helping readers. Keep the distinction in the route design rather than attempting to repair it with inconsistent canonical tags later. #### Audit complete coverage Compare the published article list with the union of entries reachable through the archive. Find omissions and repeated records, and verify all navigation targets exist in the export. Test with JavaScript delayed and at a narrow viewport. The collection is complete when a visitor can reach every intended article through a predictable path, not merely when the first page looks finished. Sources: - [Google: pagination and incremental loading](https://developers.google.com/search/docs/specialty/ecommerce/pagination-and-incremental-page-loading): Reference source. ### Manage File Preview URLs Without Memory Leaks Canonical URL: https://ourjs.in/blog/file-object-url-lifecycle/ Author: Nayan Kumar. Published: 2026-10-26. Category: Browser APIs. Create, replace and revoke object URLs at the right point in image preview and download workflows. #### Understand what an object URL represents URL.createObjectURL creates a browser-managed URL for a Blob or File. It gives an image element or download link something it can reference without uploading the file to a server. That URL is a temporary handle, not a durable path to the original document. Do not store it as a permanent database value or assume it will work in another browser session. #### Give the URL a clear owner Consider an avatar preview where the visitor chooses a file several times. Each choice can create a new object URL. Keep the active URL with the component or operation that displays it. When replacing the preview, retire the previous handle after it is no longer needed. Ownership should be obvious enough that another feature cannot accidentally revoke a URL still used by a download control. #### Revoke only after the interaction is finished Calling revokeObjectURL immediately after assigning a preview can break loading or later user actions. Instead, connect cleanup to the preview being replaced, removed or unmounted. A generated download link may need its URL to remain valid while the link is available. The right lifetime follows the visible feature, not an arbitrary timeout guessed to be long enough. #### Handle failures and replacement races A failed conversion should not leave a download button pointing to an earlier file while describing the new input. Clear or label stale results deliberately. If conversions can overlap, ensure that a slower old operation cannot install a new active URL after a newer operation has finished. Cancellation or an operation identifier can keep result ownership aligned with the current selection. #### Distinguish other URL representations A data URL embeds encoded data in the string, while an object URL refers to browser-managed data. They have different size and lifecycle characteristics. Do not call revokeObjectURL on every arbitrary URL as a generic cleanup ritual. Keep the representation visible in the code contract, especially when a QR generator produces data URLs while an image converter produces Blob-backed URLs. #### Verify repeated selection behavior Choose several files in succession, remove a preview, generate a replacement output and navigate away. Confirm that the currently displayed image and filename still agree. Inspect memory during a longer sequence if large files are involved. A single successful preview proves little about cleanup; the useful check is whether repeated use remains stable and old resources become eligible for release. Sources: - [MDN: URL.revokeObjectURL](https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL_static): Reference source. ### Model UI States with TypeScript Discriminated Unions Canonical URL: https://ourjs.in/blog/typescript-union-narrowing/ Author: Nayan Kumar. Published: 2026-10-26. Category: TypeScript. Replace conflicting booleans with explicit loading, success and error states that narrow safely. #### Look for impossible combinations A screen with loading, failed and loaded booleans can accidentally mark all three as true. The renderer then needs precedence rules that are not visible in the data model. A union can describe the actual alternatives directly. Instead of allowing every boolean combination, define idle, loading, success and error variants whose fields match what each state genuinely knows. #### Give each variant a shared discriminant Use a shared field such as status with a different literal value in each variant. A success variant can contain records, while an error variant contains a message. Checking state.status then narrows the available fields in the branch. This makes it harder to read records from a state that only promises a failure description, without scattering optional access through the component. #### Work through a search example Imagine a project search where success includes a query and a results array. Store those together so the heading and rows describe the same search. An empty results array is still a successful response, while an error means the answer is unknown. Keeping these meanings separate avoids displaying No projects found when the request actually failed to reach the server. #### Keep transitions intentional Write down which events can move the screen between variants: submitting a query, receiving the current result, cancelling, or retrying. A discriminated union describes valid shapes, but it does not automatically enforce the entire transition graph. Keep asynchronous completion tied to the correct operation so a stale result cannot replace a newer loading or success state simply because its type is valid. #### Use exhaustive handling where it helps A switch over the discriminant can make every variant visible during review. An exhaustive never check can surface a missing branch when a new variant is added. Avoid forcing every property into a shared optional bag merely to simplify one call site. That approach weakens the contract and recreates the uncertainty the union was meant to remove. #### Verify both typing and behavior Create an example of every variant and confirm the renderer handles each one. Intentionally try reading success data in the error branch and let the compiler reject it. Then test real interactions, because TypeScript cannot prove that a request result belongs to the current query. Static checking and lifecycle tests answer different questions and work best when both reflect the same state model. Sources: - [TypeScript: narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html): Reference source. ### Optional Chaining and Nullish Defaults Without Hidden Bugs Canonical URL: https://ourjs.in/blog/optional-chaining-nullish/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Keep zero, false and empty text meaningful while safely reading genuinely optional values. #### Define what missing means A form value of zero may be valid, a checkbox value of false may be intentional, and an empty string may mean the user cleared a field. Treating every falsy value as missing can erase those choices. Before choosing a defaulting operator, describe which values your contract accepts and which values represent absence. Syntax should follow that decision. #### Default only null or undefined when appropriate The nullish coalescing operator uses the fallback for null or undefined, preserving other values. For a pagination setting, pageSize ?? 20 leaves zero untouched, while pageSize || 20 replaces it. Whether zero should be accepted is a separate validation decision. Keeping defaulting and validation distinct makes a settings screen easier to explain and test. #### Read optional branches carefully Optional chaining can read profile.address?.city without throwing when address is absent. It does not confirm that the remaining value has the correct type or a meaningful value. An API returning city as an object still needs validation. Use the operator for an intentionally optional branch, not as a substitute for understanding the structure of an external response. #### Keep boundaries honest Consider an analytics card where metrics?.activeUsers ?? 0 displays zero. That may be correct for a known empty result, but misleading during a failed request or before data loads. Represent loading, unavailable and empty states separately if they mean different things to the reader. A calm-looking fallback should not conceal that the application does not know the answer. #### Avoid accidental grouping and access mistakes Keep a chain readable instead of mixing several levels of access, calls and fallbacks in one dense expression. An optional method call still requires a callable value when a non-null value exists. Similarly, adding parentheses can end the optional portion of a chain before later access. Extract intermediate values when the behavior is not obvious during review. #### Build a small truth table Verify the expression with undefined, null, zero, false, an empty string and a valid value. Then add malformed external data and a network failure to the screen-level checks. Write down the expected label for each situation. This modest exercise often catches bugs earlier than a test that only supplies the usual happy-path object. Sources: - [MDN: nullish coalescing operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing): Reference source. ### Organize Angular Reactive Forms Around the Data Model Canonical URL: https://ourjs.in/blog/angular-reactive-forms/ Author: Nayan Kumar. Published: 2026-10-26. Category: Angular. Make controls, validation rules and submission state explicit in editable Angular workflows. #### Define the editable model first A form should describe what a person can edit, not simply mirror every property returned by an API. For a project inquiry, name, email and message are editable while an internal record identifier may not be. Write down the draft shape and submission shape separately. That distinction prevents accidental exposure or modification of fields that belong to the application rather than the visitor. #### Create controls and groups intentionally Reactive forms use explicit control objects that can be combined into groups and arrays. Associate the template with that model using the relevant form directives. A group can represent the inquiry fields, while a FormArray may suit an editable list whose number of entries changes. Keep the form structure close to the feature’s editing responsibilities instead of scattering unrelated controls across services. #### Use validation to explain constraints A required rule and an email-format rule answer different questions. Show the appropriate message based on the current control state and the chosen validation timing. Do not display every possible error at once or mark a new untouched form as a failure before the person begins. Associate visible error text with the corresponding field so correction remains understandable beyond its border color. #### Handle nullable and disabled values deliberately Typed reactive forms can make assumptions about values more visible, but the runtime editing states still matter. Decide how reset affects values and whether a field is nullable. Disabled controls also require care when constructing submission data. Use the model’s relevant APIs and an explicit adapter rather than assuming every value currently displayed is included in the same way in a plain form value. #### Keep pending submission separate from validation A valid draft may still fail to save because the network or server rejects the operation. Show a pending state while the request runs, prevent accidental duplicate submission where needed, and retain the draft after failure. A server-side field error should be mapped to the relevant input when possible. Client validation helps entry but does not replace server enforcement of business rules. #### Verify edits, reset and recovery Test partial entry, invalid email, successful correction, form reset and adding or removing dynamic rows. Include a server failure after a valid submission and confirm the visitor can retry without losing work. Inspect both the form model and rendered labels. A form architecture is useful when its value transitions are predictable and its feedback helps the person complete the task. Sources: - [Angular: reactive forms](https://angular.dev/guide/forms/reactive-forms): Reference source. ### Place Next.js Client Boundaries Around Interaction, Not Entire Pages Canonical URL: https://ourjs.in/blog/nextjs-server-client-boundaries/ Author: Nayan Kumar. Published: 2026-10-26. Category: Next.js. Keep content and metadata on the server side while giving stateful controls the browser capabilities they need. #### Start from responsibilities A page often contains several different jobs: explaining a topic, reading public data, handling a button and responding to browser state. These jobs do not all need the same execution environment. In the App Router, decide which part needs interactivity, then place the client boundary around that part rather than adding use client to the entire page by habit. #### Keep descriptive content straightforward An article heading, publication date and paragraphs can remain in a Server Component. A filter box or image-processing form needs client state and event handlers. This separation keeps the architecture close to the user task. It also makes it easier to inspect which dependencies enter the client module graph instead of treating the whole application as one browser bundle. #### Use a tool page example A resizer route can read the tool record, generate metadata and render instructions on the server side. Its ToolRunner child handles the selected file, quality settings and download URL in the browser. The child receives a simple slug or configuration object. It does not need the entire article collection just to decide which input fields to show. #### Respect the data crossing Props crossing a server-to-client boundary need to be serializable in the supported model. Avoid passing arbitrary callbacks or database objects as if both sides share one runtime. Shape data deliberately: labels, options and identifiers are often enough. Keep browser APIs out of module initialization and server rendering, even in a Client Component that will later hydrate in the browser. #### Do not equate client with browser-only HTML Client Components can participate in prerendering for the initial load. The directive establishes a module boundary; it does not mean that every expression is safe to evaluate only in a browser. Access window, localStorage or document in an appropriate effect or event handler, and ensure the initial render is consistent enough to hydrate correctly. #### Review the actual bundle and behavior Inspect build output and the browser network panel after moving a boundary. Verify that the controls still work, page metadata remains available and direct navigation renders meaningful content. Optimize based on the dependencies and work you removed, not the number of server files you created. A boundary is useful when it clarifies responsibilities and reduces unnecessary client work without breaking the experience. Sources: - [Next.js: Server and Client Components](https://nextjs.org/docs/app/getting-started/server-and-client-components): Reference source. ### Prepare a Static Website Rollback Before the Release Needs One Canonical URL: https://ourjs.in/blog/rollback-static-deployment/ Author: Nayan Kumar. Published: 2026-10-26. Category: DevOps. Retain complete artifacts and restore coherent document and asset versions instead of copying a few old files over a broken release. #### Define what rollback means A rollback restores a known working release and its required configuration. For a static website, that includes HTML, scripts, styles, metadata files and referenced assets. Replacing only the homepage may leave deep routes on the broken version. Write down the restoration unit so the team can act on a specific artifact rather than improvising a collection of individual file copies. #### Retain identifiable release artifacts Store the previous tested output with its source revision, build inputs and publication time. A Git commit alone may not reproduce the same files later if dependencies or remote content have changed. Retaining the artifact reduces that uncertainty and preserves the relationship between what was tested and what can be restored. Decide retention according to the site’s deployment process. #### Consider an asset compatibility example Suppose release B publishes new HTML that references app.b2.js. A rollback to release A must restore HTML referencing app.a1.js while keeping that asset available. Existing browser sessions may still request B’s assets after the switch. Retaining both versions for a suitable overlap avoids turning a rollback into a new set of missing-file errors. #### Include cache behavior in the plan Changing origin files does not instantly change every cached response. Know which document paths may need revalidation or a targeted invalidation, and distinguish them from immutable versioned assets. Avoid purging first if the origin still serves the broken version, because the next request can refill the cache with the same content. Coordinate restoration and cache updates in a deliberate order. #### Separate reversible frontend changes Static file restoration cannot reverse a backend schema change, a sent message or a third-party side effect. Before release, identify whether the frontend depends on a new API contract that the older version no longer understands. Keep compatible rollout windows where possible and document cases where a forward fix is safer than restoring an incompatible client. #### Practice the verification path Test the recovery procedure in an appropriate nonproduction environment. After a real restoration, inspect the release identifier, homepage, deep routes and main interactive task. Monitor missing assets and runtime errors, and record why the release was rolled back. A practiced, evidence-based process is more useful than a promise that someone could always upload the old files if necessary. Sources: - [AWS: versioned files and release control](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/UpdatingExistingObjects.html): Reference source. - [GitHub: deployment artifacts](https://docs.github.com/en/pages/getting-started-with-github-pages/using-custom-workflows-with-github-pages): Reference source. ### Prevent Layout Shifts by Reserving the Space Your Content Will Need Canonical URL: https://ourjs.in/blog/prevent-layout-shifts/ Author: Nayan Kumar. Published: 2026-10-26. Category: Performance. Stabilize images, async messages, fonts and embeds so content does not move unexpectedly while someone reads or clicks. #### Watch the page over time A screenshot shows the final layout, but it cannot reveal how the page arrived there. Observe loading and interaction to find content that moves unexpectedly. An image, late banner or font swap can displace a link just as someone tries to select it. Cumulative Layout Shift measures qualifying visual instability, while direct observation helps explain which interface decision caused it. #### Reserve image and embed frames Provide intrinsic image dimensions or an appropriate aspect-ratio frame before the asset arrives. Apply the same idea to videos, maps and other embeds. A responsive layout can change width while preserving the expected ratio. Avoid reserving a generic height that bears little relation to the content, because the correction after loading can still shift everything below it. #### Plan a practical result panel Suppose a browser tool displays a processing summary after a button is pressed. Place the result in a logical area that does not unpredictably insert itself above the current control. Reserve a small status region where useful, and allow substantial output to grow in a predictable direction. Do not hide an important message merely to keep a metric quiet. #### Review fonts and late styling Different font metrics can change line wrapping and block heights when the intended font arrives. Choose sensible fallbacks and delivery strategies, then test the actual transition. Similarly, critical layout rules arriving after initial paint can cause a large rearrangement. A stable design needs its structural assumptions available early, not just a final stylesheet that eventually looks correct. #### Avoid surprise insertions above content Promotional banners, consent interfaces and asynchronous notices need a placement strategy. Reserve their region, overlay carefully when appropriate, or add them where they do not unexpectedly push the current reading position. Consider focus and accessibility alongside visual stability. An overlay that covers the only available submit button trades one usability problem for another rather than solving the experience. #### Test more than the opening second Scroll, open details, trigger validation and let delayed content finish. Use layout-shift tooling to connect movement with its contributing elements, and distinguish expected interaction changes from unexpected instability. Check narrow screens where a small width change can add several lines of text. Retest after real content updates, because a layout that is stable with short placeholders may move with longer headings. Sources: - [web.dev: optimize Cumulative Layout Shift](https://web.dev/articles/optimize-cls): Reference source. ### Profile React Rendering Before Adding Memoization Canonical URL: https://ourjs.in/blog/react-render-performance/ Author: Nayan Kumar. Published: 2026-10-26. Category: React. Investigate slow interactions by measuring render work, state placement and browser cost separately. #### Choose an interaction worth measuring A vague claim that a page rerenders too much is difficult to act on. Pick a concrete interaction, such as typing into a table filter or opening a product drawer, and describe what feels delayed. Record the device and data size used for the check. A useful investigation connects the visitor’s waiting time to observable work rather than counting renders without context. #### Separate React work from browser work React can spend time calculating component output, while the browser can spend time on style calculation, layout, painting or unrelated JavaScript. An expensive chart library may also perform work outside React. Use appropriate profiling tools to distinguish these costs. Reducing one component’s render count will not solve a large synchronous image conversion or an avoidable layout operation somewhere else. #### Inspect a specific filtering example Suppose typing into a search box makes a large project table slow. First check whether filtering is repeated unnecessarily, whether the input state is owned by a component wrapping unrelated expensive content, and whether every row performs a costly transformation. Moving the input’s ownership closer to its consumers or precomputing stable display data may be more useful than applying memo to every component. #### Treat memoization as a targeted cache A memoized component or calculation can skip work when its relevant inputs remain equivalent under the chosen rules. A freshly created object prop may prevent the cache from helping. More importantly, the feature must remain correct without depending on a cache to preserve state semantics. Add memoization around a measured cost, then verify that the actual interaction improves. #### Keep measurement conditions comparable Development checks and debugging tools can add overhead, so avoid presenting one development trace as a universal production result. Compare the same action with representative data and similar device conditions. Use React profiling to locate render costs and browser performance tools for end-to-end behavior. Record enough context that another developer can repeat the investigation instead of trusting an unexplained before-and-after number. #### Verify correctness after optimization A skipped render is not a success if a label or permission state becomes stale. Repeat the original interaction, then change every input that should update the optimized component. Include rapid edits and navigation if the feature supports them. The final result should preserve correct output while reducing the measured bottleneck, with a short explanation of why that particular change was effective. Sources: - [React: Profiler reference](https://react.dev/reference/react/Profiler): Reference source. ### Progressive Enhancement: Keep Content Useful Before JavaScript Runs Canonical URL: https://ourjs.in/blog/progressive-enhancement-content/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Build readable pages first, then layer on filtering, animation and richer interactions without making the content depend on them. #### Define the useful baseline A portfolio’s baseline is its introduction, project evidence, contact route and readable articles. Those should not wait for a decorative animation script to finish. Write semantic HTML with ordinary links and enough content to explain the page. Enhancements can make that experience more convenient, but they should not be the only way to discover what the page contains. #### Add behavior around existing content A tools directory can render its full list first, then add category filtering and search after the client code becomes available. The original links remain useful while the script loads. In contrast, a directory that begins as an empty container offers nothing when loading fails, even if its finished interaction is polished. #### Keep motion as a presentation layer An assembly illustration can start in its completed arrangement and animate its pieces when the environment supports it. Text should remain visible if the observer or animation library fails. Avoid an initial state that leaves every section transparent until a script changes a class. The final composition should be a valid design, not a temporary failure state. #### Be explicit about application requirements Some tools genuinely require JavaScript to process an image or format JSON. Progressive enhancement does not mean pretending those operations work without it. Keep the tool’s explanation and instructions readable, and provide a clear message when the interactive capability is unavailable. Distinguish a real functional requirement from an avoidable dependency in the surrounding page. #### Handle optional capabilities separately Clipboard access, browser storage and image encoders can fail independently. A failed copy action should leave output selectable. An unavailable preference store should not prevent changing the current theme. A missing export format should produce an explanation instead of a mislabeled file. These small fallbacks preserve the task even when a convenience feature is absent. #### Test deliberate failures Disable scripts, block an optional asset, deny clipboard permission and use reduced-motion mode. Check what remains usable and what is explained honestly. Follow a link before hydration finishes and open a deep article fragment. Resilience becomes concrete when the page still communicates its purpose and offers sensible next steps under conditions beyond the perfect development preview. Sources: - [MDN: progressive enhancement](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement): Reference source. ### Promise Error Handling That Keeps Failures Visible Canonical URL: https://ourjs.in/blog/promise-error-handling/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Design promise chains with clear ownership of errors, honest UI feedback and reliable cleanup. #### Choose who owns the failure An asynchronous helper should either recover with a useful value or reject so its caller can decide what to show. Mixing both approaches without a contract produces confusing behavior: a helper logs an error and returns undefined, while the screen mistakes the fulfilled promise for a successful save. Decide what successful completion means before adding catch handlers. #### Return every dependent operation Consider a report workflow that loads records, creates a file and saves it. If a then callback starts file creation but does not return its promise, the outer chain cannot wait for that step or observe its rejection. Return the next operation, or await it inside an async function, so the workflow remains one inspectable chain from beginning to end. #### Recover only where recovery is meaningful A failed optional avatar request might reasonably use an initials image. A failed invoice save should not silently substitute an empty object. Make fallbacks specific to the feature and visible when they affect what the user can do. If a catch handler cannot restore the promised result, rethrow the error rather than allowing accidental success. #### Separate feedback from diagnostics A user needs an explanation such as The report could not be generated, plus a sensible next action. A developer may need the failing stage and request identifier. Do not expose access tokens, raw personal records or internal stack traces in the interface. Keep diagnostic context useful without turning ordinary failure handling into an unintended data disclosure. #### Use cleanup without changing the outcome Put pending-state cleanup in finally when the action should stop looking busy regardless of success or failure. A finally handler is not the place to invent a replacement result. Also avoid returning from finally in a way that hides a thrown error. Keep result assignment in the success path and error feedback in the failure path. #### Exercise each failure boundary Test the loader rejecting, the transformer throwing and the download step failing independently. Confirm that the busy indicator clears, the previous valid result remains understandable, and repeated attempts still work. Watch for unhandled promise rejections in the console. A caught error is only handled properly when the application reaches a deliberate, useful state afterward. Sources: - [MDN: using promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises): Reference source. ### Publish a Static Website with Separate GitHub Actions Build and Deploy Jobs Canonical URL: https://ourjs.in/blog/github-actions-static-site/ Author: Nayan Kumar. Published: 2026-10-26. Category: DevOps. Use an uploaded build artifact, explicit Pages permissions and a deployment dependency that preserves what was tested. #### Choose the publishing source GitHub Pages can publish through a custom Actions workflow when the repository is configured for it. Decide whether the site is a user site or a project site because the public base path affects links and assets. A build that works at the domain root can fail when deployed under a repository subdirectory if that path was never considered. #### Build in a dedicated job Check out the intended revision, set up the runtime and install dependencies using the lockfile. Run the checks appropriate to the project, then generate the static output. For a Next.js export, this is the directory produced by the export build, not the source tree and not the development cache. Upload only the files the static host should serve. #### Pass an artifact to publication The deploy job should depend on the successful build and publish the uploaded Pages artifact. This creates an explicit relationship between tested output and deployed output. Use the documented official actions and review their current versions rather than copying an old workflow without understanding its permissions, required artifact format or environment configuration. #### Trace a small example failure Suppose the workflow uploads the repository root while the generated site lives in out/. The deployment step can succeed even though visitors see the wrong files or missing routes. Inspect the artifact before changing application code. Listing its top-level paths and checking for index.html, framework assets and a representative deep page can expose the packaging error immediately. #### Scope permissions and concurrency Give the deployment job the documented Pages and identity-token permissions it needs, keeping unrelated repository access out of scope. Use an environment for deployment visibility and applicable protections. Coordinate publishing runs so two releases do not compete for the same destination. Avoid logging sensitive variables while debugging permissions because build logs may have a broader audience than intended. #### Verify the resulting URL Use the deployment output to find the final public address, then check direct deep links, asset paths, the sitemap and a missing page. Test the site as a visitor rather than stopping at a green Actions summary. Keep the previous successful artifact or revision identifiable so a broken release can be investigated and restored through a deliberate publication step. Sources: - [GitHub: custom workflows for Pages](https://docs.github.com/en/pages/getting-started-with-github-pages/using-custom-workflows-with-github-pages): Reference source. - [GitHub: automatic website deployment](https://docs.github.com/en/get-started/start-your-journey/deploying-your-website-automatically): Reference source. ### React State vs Ref: Choose by What the Screen Must Show Canonical URL: https://ourjs.in/blog/react-state-vs-ref/ Author: Nayan Kumar. Published: 2026-10-26. Category: React. Keep rendered information in state and operation handles in refs without hiding updates from the UI. #### Ask whether the value affects rendering If a value determines the text, layout or controls shown on screen, it usually belongs in state or is derived from state and props. A ref can remember a mutable value without requesting a render. That makes it useful for operation handles, but dangerous as an invisible replacement for data the visitor expects to see update. Choose by responsibility rather than by perceived performance. #### Compare two timer values A stopwatch needs an elapsed-time display and an interval identifier. The displayed time changes what React renders, so state is a suitable home. The interval identifier exists so code can later clear that timer; changing it should not redraw the screen. A ref can hold that handle across renders while keeping it available to event handlers and cleanup logic. #### Remember that state is a render snapshot Calling a state setter schedules a later render; it does not rewrite the local variable captured by the current handler. When the next value depends on the previous value, a functional update can make that dependency explicit. A ref’s current property is mutable immediately, but using it to bypass the state model can create a screen that displays an outdated value. #### Use refs for stable external ownership A DOM node, pending animation-frame identifier or current AbortController can be appropriate ref values. These are handles into work outside the declarative screen. Keep creation and cleanup aligned with the operation that owns them. A ref persisting across renders does not automatically cancel an old timer, disconnect an observer or make an external object safe to reuse. #### Keep rendering pure Avoid reading or changing mutable ref values during rendering when the component’s output depends on those changes. Such behavior makes the output harder to predict and can conflict with React’s rendering assumptions. Prefer state for visible decisions and effects or events for external coordination. A ref should clarify an escape hatch rather than turn the component into a collection of hidden mutable fields. #### Verify visible and invisible updates separately For the stopwatch example, start, stop and restart several times. Confirm the number changes while running, stops reliably and does not create duplicate intervals. Navigate away and verify cleanup. Then inspect whether changing an operation handle causes unnecessary work. The useful distinction is not which hook is faster in isolation, but whether the code accurately represents the screen and its resource lifecycle. Sources: - [React: referencing values with refs](https://react.dev/learn/referencing-values-with-refs): Reference source. ### Reserve Image Space to Keep Page Layouts Stable Canonical URL: https://ourjs.in/blog/reserve-image-aspect-ratio/ Author: Nayan Kumar. Published: 2026-10-26. Category: Images. Give images a predictable footprint before they load so headings, buttons and paragraphs stay in place. #### Notice what moves during loading A project thumbnail may arrive after the surrounding text has already rendered. If its container initially has no height, the image pushes everything below it downward. That movement is especially disruptive when someone has begun reading or is about to activate a link. Reserving the expected image space prevents this particular source of instability. #### Provide the intrinsic dimensions When the source dimensions are known, include width and height attributes on the image. They communicate the intrinsic ratio without requiring the final displayed image to use those exact pixel dimensions. Responsive CSS can still set width:100% and height:auto. The browser can use the relationship between the dimensions while the file is being fetched. #### Use a ratio for deliberate frames A project grid might require consistent 16:10 thumbnail frames even when source images differ. Give the wrapper an aspect-ratio and place the image inside it. Combine that with object-fit:cover only if cropping is acceptable. The frame ratio describes the design; the image’s intrinsic dimensions describe the source. Keep those responsibilities distinct. #### Plan for absent or failed images A reserved frame should not become a confusing blank block when a file fails. Use a suitable background and ensure the adjacent title still identifies the project. For an informative image, the alternative text must remain useful. Do not replace a failed chart with a decorative placeholder and assume its information has been preserved. #### Avoid contradictory sizing rules A fixed CSS height, a different wrapper ratio and an image set to height:auto can fight one another. Inspect the actual box receiving each declaration. For example, an absolutely positioned image can fill a ratio-controlled wrapper, while an ordinary responsive image may need no wrapper at all. Prefer the simpler structure when it meets the design requirement. #### Test with slow delivery Throttle the connection in developer tools and watch the page while images load. Check that reserved frames stay consistent across narrow and wide layouts. Follow an anchor below an image and verify that late loading does not displace the target. Layout stability is easier to judge during loading than from a screenshot taken after every asset has arrived. Sources: - [MDN: aspect-ratio](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/aspect-ratio): Reference source. ### Responsive CSS Grid Cards Without a Breakpoint for Every Screen Canonical URL: https://ourjs.in/blog/css-grid-responsive-cards/ Author: Nayan Kumar. Published: 2026-10-26. Category: CSS. Build a flexible project grid that adapts to its container and survives long titles, narrow screens and missing images. #### Start from the smallest useful card A grid should be designed around what each card needs to communicate. A project card might contain a thumbnail, title, short description and link. Try that content in a narrow single column before choosing the desktop arrangement. If the card only works with a short title, the layout is not ready for real content. #### Let available space set the column count A useful starting rule is grid-template-columns: repeat(auto-fit, minmax(min(100%, 17rem), 1fr)). The minimum gives a card room to breathe, while the inner minimum prevents that size from exceeding a tiny container. The flexible maximum shares remaining space. This creates natural column changes without a separate media query for each possible width. #### Use gaps instead of card margins Apply spacing through the grid’s gap property so the outer container stays predictable. For example, a 1.25rem gap separates rows and columns consistently without extra margins on the last card. Give the page its own inline padding. Separating container spacing from card spacing makes later changes easier to reason about. #### Keep the card’s internal structure stable Cards with different description lengths can still align their final action. Make each card a column flex container and allow the action area to use margin-block-start:auto. Reserve the thumbnail’s aspect ratio so its arrival does not push text downward. Do not force a fixed overall card height if that risks hiding longer content. #### Handle content that resists shrinking A long URL, code token or unbroken project name can stretch a track unexpectedly. Inspect the relevant item’s minimum width and allow wrapping where it is appropriate. A min-width:0 rule on an inner wrapper can solve a different problem from overflow-wrap on text. Neither should be added blindly to every descendant. #### Test the spaces between screenshots Drag the viewport gradually rather than checking only a phone and a desktop preset. Look for the moment a third column becomes too cramped, and inspect the last incomplete row. Also try one card, nine cards, enlarged text and a translated heading. The grid should adapt to its content instead of depending on a perfect demo dataset. Sources: - [MDN: grid-template-columns](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/grid-template-columns): Reference source. ### Responsive Images: Choose Between Srcset, Sizes and Picture Canonical URL: https://ourjs.in/blog/responsive-picture-srcset/ Author: Nayan Kumar. Published: 2026-10-26. Category: Images. Serve suitable image candidates and use art direction only when the composition needs to change. #### Separate resolution from composition A small screen may need fewer image pixels, or it may need a different crop. Those are different requirements. Resolution switching offers several sizes of the same image; art direction changes the composition. Decide which problem you have before adding a picture element and a collection of sources that are difficult to maintain. #### Prepare useful source candidates For a project thumbnail, export a few widths that cover the real layout rather than every possible device dimension. A 480-pixel, 960-pixel and 1440-pixel version might fit a particular design. Inspect each output visually and compress it appropriately. Candidate filenames should make it clear which asset was generated at which width. #### Describe the layout honestly With width-descriptor srcset candidates, sizes tells the browser the image’s expected display width under different conditions. If the card occupies one third of a wide container, declaring that it always fills the viewport can lead to unnecessarily large downloads. Base the sizes expression on the implemented layout, including its maximum width and page padding. #### Use picture for intentional art direction Suppose a desktop hero shows a wide workspace, while the mobile design needs a close crop of the central object. A picture element can select the appropriate source for those conditions, with an img fallback that still carries alt text and dimensions. Keep the meaning consistent even when the visual framing changes. #### Do not make every image lazy Images far below the first screen are good candidates for deferred loading. The main visible hero image often has a different priority. Apply loading behavior according to the image’s role rather than adding lazy loading to every img element through a shared component. Also reserve dimensions so choosing a candidate does not cause the layout to jump. #### Inspect what the browser chose Use the network panel and the image’s currentSrc to see which candidate is actually delivered at each layout width. Test different device pixel ratios where possible. Check for missing files and unnecessarily large downloads. Responsive markup is useful only when it accurately describes real assets and the space those assets occupy on the page. Sources: - [MDN: responsive images](https://developer.mozilla.org/en-US/docs/Web/HTML/Guides/Responsive_images): Reference source. ### Robots.txt and Noindex Solve Different Problems Canonical URL: https://ourjs.in/blog/robots-txt-vs-noindex/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Choose between crawling controls and indexing directives without accidentally preventing a crawler from reading your instruction. #### Distinguish the two decisions Crawling is the process of requesting a resource; indexing concerns whether a page is included in a search index. A robots.txt rule can restrict compliant crawlers from fetching a path. A noindex directive tells a supporting search engine not to index the page it has fetched. Keeping these decisions separate prevents contradictory configurations. #### Let the directive be discovered A crawler generally needs access to a page to read its HTML robots meta tag or indexing response header. Blocking the same URL in robots.txt can prevent that instruction from being seen. Do not assume that combining every restrictive control makes removal more reliable. Establish which mechanism fits the desired outcome and verify its documented behavior. #### Work through a preview example Suppose a public event preview should remain accessible to reviewers but absent from search results. A crawlable page with the appropriate noindex directive addresses indexing, while an authenticated preview addresses actual privacy. These are different requirements. A robots exclusion alone is not a lock, and a noindex tag does not prevent someone from opening a shared link. #### Review page-level inheritance Staging sites often begin with restrictive settings. Before publishing, inspect whether a root layout, HTTP header or hosting dashboard still applies noindex to every page. Conversely, avoid removing restrictions from a draft route merely because the main website is ready. Classify routes deliberately instead of flipping one global setting without checking what inherits it. #### Keep resources available A page can be crawlable while scripts, images or styles needed to understand it are blocked. Review resource rules as well as document rules. For a client-enhanced tool page, the useful introductory HTML should remain readable, and necessary rendering assets should not be excluded accidentally by a broad folder pattern copied from another project. #### Verify with actual responses Fetch robots.txt from the production origin and inspect both HTML meta tags and response headers on representative URLs. Test an allowed article, an intentionally excluded page and a missing route. After release, use search inspection tools to confirm observed behavior. Changes to discovery and indexing take processing time, so distinguish an outdated report from an unchanged live directive. Sources: - [Google: robots.txt introduction](https://developers.google.com/search/docs/crawling-indexing/robots/intro): Reference source. - [Google: noindex](https://developers.google.com/search/docs/crawling-indexing/block-indexing): Reference source. ### Scroll Reveals with Intersection Observer and a Readable Baseline Canonical URL: https://ourjs.in/blog/intersection-observer-reveals/ Author: Nayan Kumar. Published: 2026-10-26. Category: Animation. Trigger section entrances near the viewport while keeping the document usable before scripts run. #### Keep the baseline visible Start with normal HTML whose text and links can be read immediately. A reveal animation should add a little movement as a section enters view, not decide whether the section exists. This makes the page more resilient when scripts fail, a user disables motion, or someone opens a deep link directly to a later heading. #### Observe visibility instead of every pixel Intersection Observer reports changes in how a target intersects a root such as the viewport. It is well suited to knowing when a section is near enough to animate. It is not designed to provide an exact per-pixel scrolling position for a continuous parallax scene. Use the mechanism that matches the effect you actually need. #### Choose a modest entrance For a portfolio feature row, a short translation from roughly two dozen pixels below its final position can be enough. Keep the text readable during the transition and avoid a large zoom that changes the apparent reading target. A brief entrance should support the page’s hierarchy rather than making every paragraph demand attention. #### Use one observer for similar targets A single observer can watch several sections that share the same configuration. When a once-only entrance finishes or starts, unobserve that target so it does not repeat every time the reader scrolls slightly backward. Choose a threshold that works with tall content; waiting for an entire long article section to enter may never trigger. #### Clean up when the page changes In a component application, disconnect observers when their owner is removed and cancel any animations that should not continue. Navigation can replace the target elements while the layout remains mounted. Refresh the observed target list for the new route without accumulating callbacks that still reference an older page’s DOM nodes. #### Test the inconvenient entry points Reload halfway down a page, follow an anchor to the last section and return through browser history. Check a short viewport and reduced-motion mode. Confirm the observer is not needed for links to work or for content to appear. The best reveal implementation leaves a complete experience behind when the enhancement is entirely unavailable. Sources: - [MDN: Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API): Reference source. ### Semantic HTML Landmarks: Give Every Page a Clear Structure Canonical URL: https://ourjs.in/blog/semantic-html-landmarks/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Use native page regions to make a portfolio easier to navigate with assistive technology and easier to maintain. #### Start with the page’s purpose Before adding layout classes, write the regions your page actually needs. A portfolio usually has a site header, primary navigation, one main content area and a footer. A project detail may also have a related-work sidebar. This content map helps avoid a document filled with anonymous containers whose roles are only apparent visually. #### Choose elements for meaning Use header for introductory content, nav for a substantial navigation group and main for the page’s central subject. A footer can contain contact and copyright information. A section should represent a meaningful grouping, normally with a heading. An article should make sense as a self-contained entry, such as a journal post or project case study. #### Label repeated navigation Consider a project page with links across the top and a table of contents beside the article. Give the first navigation an accessible name such as Main navigation and the second a name such as On this page. These names describe their purpose without requiring a screen reader user to open each region and inspect its links. #### Keep the content order honest Write the DOM in the order people should read it: introduction, evidence, then next steps. Use CSS to arrange the regions without moving a visually prominent call to action far away from its logical context. A beautiful two-column arrangement still needs a sensible sequence when the columns stack or the stylesheet fails. #### Avoid adding unnecessary roles Native elements already provide many useful semantics. Adding a navigation role to nav is usually redundant; assigning button semantics to a noninteractive section is actively misleading. More landmarks do not automatically mean more clarity. If every small card becomes its own named region, the page’s navigation outline can become harder to scan. #### Verify the resulting map Inspect the accessibility tree and navigate by landmarks with a screen reader. Confirm that the central content has one clear main region, repeated navigations have distinct names, and a footer has not accidentally been placed inside the article. Finally, read the page without styles: its structure should remain understandable without relying on position, color or animation. Sources: - [MDN: landmark role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Roles/landmark_role): Reference source. ### Sequential or Parallel Async Work: Choose by Dependency Canonical URL: https://ourjs.in/blog/async-await-sequential-parallel/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Use await, Promise.all and bounded concurrency according to data dependencies and failure requirements. #### Draw the dependency graph first Before changing await statements, list which operations need the results of earlier ones. A dashboard can often load a profile and a category list independently, while a permissions request may require the profile identifier. That simple distinction determines the safe execution order. Parallel execution is helpful only when it preserves the requirements of the workflow. #### Keep dependent work sequential If a document must be created before an attachment can reference its identifier, await creation before starting the attachment request. Running both operations together would send incomplete information or require fragile guesses. Sequential code makes this dependency explicit and gives each failure a clear location. Avoid hiding the relationship behind shared mutable variables that happen to be filled later. #### Start independent work together For two unrelated read requests, create both promises and await Promise.all to receive their results together. The array of results corresponds to the input order, even when completion order differs. As an original example, a settings page can request available time zones and saved preferences concurrently, then render the form once both necessary values are available. #### Define partial success deliberately Promise.all rejects when an input rejects, but it does not automatically cancel operations already running. If individual results can still be useful, consider Promise.allSettled and inspect every status. A bulk thumbnail operation might show seven successful outputs and identify three failed files. A payment-related action would need a much more carefully designed transactional workflow rather than a generic concurrency helper. #### Bound work that grows with input Starting a request for every row in a large import can overload the browser or the receiving service. Use a queue with a limited number of active workers, and keep progress tied to finished items. Concurrency limits should reflect the actual service and device constraints. Reducing the number of requests through a batch endpoint may be better than scheduling them more cleverly. #### Verify order and recovery Use controlled delays in a local test to make operations finish in a different order. Reject one operation and check which results the interface retains. Verify that navigation or cancellation stops unnecessary work where supported. Compare the overall interaction before and after the change; shorter source code alone does not demonstrate a faster or more reliable experience. Sources: - [MDN: Promise.all](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all): Reference source. ### Set React Context Boundaries Around Real Shared State Canonical URL: https://ourjs.in/blog/react-context-boundaries/ Author: Nayan Kumar. Published: 2026-10-26. Category: React. Use context for shared dependencies without turning every local input into an application-wide update. #### Name the shared responsibility Context is useful when descendants need the same dependency or state and passing it through unrelated components becomes cumbersome. A theme preference, current session or feature-level editor state can be reasonable examples. The presence of several nested components alone is not proof that context is necessary. Begin with the actual ownership and access requirements of the feature. #### Keep a filter input near its consumers Imagine a portfolio whose search query only affects one project list. That query can live close to the list instead of entering a global provider that also wraps the footer and contact form. Local ownership reduces the number of places that can change the value. Move state upward only when a second consumer genuinely needs the same authoritative value. #### Use provider scope intentionally A provider defines the value available to descendants within its boundary. A feature-specific provider can therefore create an independent instance of state for each editor or workspace. That is different from a single root provider shared by the whole application. Document whether opening two workspaces should share a selection or maintain separate selections before choosing where the provider belongs. #### Separate values that change differently A rapidly changing draft and a rarely changing configuration do not necessarily belong in the same context object. Consumers that need one may otherwise observe updates to the other. Splitting responsibilities can improve clarity before any performance optimization. Stable object identities can matter, but memoizing a large context object does not fix an underlying contract that exposes too much unrelated state. #### Keep component dependencies visible A component that reads context has an implicit requirement on its surrounding tree. A small custom hook can provide a useful error when a required provider is missing. For reusable visual components, explicit props may remain clearer than context. Composition can also remove prop forwarding without introducing a shared mutable environment, so consider those alternatives during component design. #### Verify isolation and update behavior Render the feature with two independent providers and confirm that changing one instance does not affect the other. Check the missing-provider behavior and profile a high-frequency input if responsiveness is a concern. Test that nested overrides do what their names suggest. A good boundary makes both state ownership and the expected impact of an update obvious to a reviewer. Sources: - [React: passing data with context](https://react.dev/learn/passing-data-deeply-with-context): Reference source. ### The JavaScript Event Loop: Predicting What Runs Next Canonical URL: https://ourjs.in/blog/javascript-event-loop/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Trace synchronous code, promise callbacks and timers so browser interactions stay understandable and responsive. #### Start with a small timeline When a click handler runs, its ordinary statements finish before another task can interrupt that JavaScript execution. Browser work, timers and promise reactions introduce scheduling boundaries around that execution. Thinking in timelines is more useful than calling everything asynchronous: write down when an operation starts, when it becomes ready, and when its callback can actually run. #### Predict a concrete example Imagine a button that logs start, schedules a zero-delay timer to log timer, queues a resolved promise reaction to log promise, and finally logs end. In this ordinary example, start and end appear first, promise follows, and timer comes later. A zero delay means the timer becomes eligible; it does not mean the callback interrupts the current handler. #### Connect scheduling to visible feedback Suppose an export button changes its label to Preparing and immediately calculates a large report synchronously. The browser may not paint the new label before the calculation finishes. Updating the DOM does not itself guarantee a rendered frame. Break genuinely large work into manageable pieces, or move suitable computation to a worker, while keeping cancellation and progress meaningful. #### Treat microtasks with care Promise reactions are processed through the microtask mechanism. A chain that continually schedules more microtasks can keep the browser busy and delay other work. Replacing a long loop with thousands of resolved promises is therefore not an automatic responsiveness improvement. Choose a scheduling strategy based on the opportunity the browser needs, rather than the syntax that looks asynchronous. #### Avoid timing assumptions in features A debounce delay, animation timeout or network callback should not be treated as an exact clock. Background tabs, device load and browser policies can change callback timing. For a countdown, compare timestamps against a deadline instead of subtracting one on every timer tick. For loading states, tie completion to the operation rather than a guessed timeout. #### Verify with observations Run the logging example in an isolated page, then record a performance trace while triggering an expensive action. Look for long tasks and whether feedback appears before work completes. Test repeated clicks and navigation during processing. The useful outcome is a clear explanation of which work blocks the next interaction, followed by a measured change that removes that blockage. Sources: - [MDN: JavaScript execution model](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Execution_model): Reference source. ### Theme a Website with Semantic CSS Custom Properties Canonical URL: https://ourjs.in/blog/css-custom-properties-theming/ Author: Nayan Kumar. Published: 2026-10-26. Category: CSS. Create a small token system that lets branded pages and light product pages share components without a tangle of overrides. #### Name colors by responsibility A variable such as --surface explains where a color belongs; --purple-900 only describes its appearance. Keep both kinds if you need a palette and semantic layer. For example, a product theme can map its surface to silver and its text to plum without requiring every component to know the exact hexadecimal values. #### Define a compact starting set Begin with background, surface, text, muted text, border, accent and focus colors. Add spacing or radius tokens only when repeated usage justifies them. An enormous token catalog can become as hard to maintain as scattered literals. The first goal is to make a shared button or card express its intent consistently. #### Scope variations near their context Place default tokens on the root, then redefine semantic values on a theme wrapper. A light tool workspace might set --surface:#DDE3E8, --text:#3A0F34 and --accent:#EAAA00. Descendant components can inherit those values. This is more predictable than searching for every dark background class and overriding each one separately. #### Remember that inheritance is selective Custom properties inherit by default, but their effects depend on where they are consumed. If a component hard-codes its label color, changing --text does nothing to that label. Inspect the complete component state: default, hover, focus, disabled and error. A theme is incomplete when only its large background panels follow the token system. #### Use fallbacks with a clear purpose A declaration like color:var(--control-text, var(--text)) provides a useful fallback when a component-specific value is absent. It does not validate whether the supplied value creates a readable contrast. Keep fallback chains short enough to trace. If a custom property contains an invalid value for its destination property, debugging may require inspecting computed styles. #### Verify themes as combinations Review text and background pairs in the actual interface rather than testing each palette swatch in isolation. Check menus, inputs, helper text and code blocks. Temporarily change one semantic token and observe which components update. That experiment quickly reveals hard-coded exceptions and helps keep future visual changes focused instead of spreading into unrelated layout rules. Sources: - [MDN: using CSS custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Cascading_variables/Using_custom_properties): Reference source. ### Transform or Layout Animation? Choose the Property That Matches the Effect Canonical URL: https://ourjs.in/blog/css-transform-vs-layout-animation/ Author: Nayan Kumar. Published: 2026-10-26. Category: Animation. Animate movement intentionally, understand what it changes, and verify performance instead of assuming every transition is cheap. #### Separate visual movement from layout Moving an element with transform changes its visual presentation without asking neighboring content to take its new position. Changing a layout property such as width can affect surrounding geometry. Choose based on the intended result. A floating decorative shape needs visual movement; an expanding content panel may need its neighbors to move as well. #### Start with a small hover example For a project card, a translateY transform of a few pixels can communicate interactivity without changing the grid tracks. Transition the transform and perhaps a border color. Keep the displacement small enough that the target remains easy to follow. A dramatic lift on every card can become distracting and cause overlaps between adjacent rows. #### Do not assume acceleration is automatic Transforms and opacity are useful candidates for efficient animation, but the complete scene still matters. Large layers, expensive shadows, filters and continuously repainting descendants can add cost. A property choice is a starting point, not a performance certificate. Inspect the page with developer tools on the devices that matter to the project. #### Avoid permanently promoting everything A broad will-change rule on every card can reserve rendering resources for elements that never animate. Add such hints only when measurement supports them, and scope them to the relevant period where practical. The goal is to make a specific interaction smooth without increasing memory use across an entire long page of otherwise static content. #### Coordinate reads and writes In JavaScript-driven motion, avoid repeatedly reading layout immediately after changing styles for many elements. Collect the measurements you need, calculate the next values, then apply updates together. RequestAnimationFrame can organize frame work, but it is not a license to perform unlimited measurements and mutations during every scroll or pointer event. #### Measure and provide an off state Record an interaction before and after a change, inspect dropped frames and check whether text remains readable during movement. Test keyboard focus as well as pointer hover. Respect reduced-motion preferences and stop offscreen decorative loops when appropriate. A simpler animation that responds reliably is more useful than an elaborate effect that interrupts navigation. Sources: - [web.dev: high-performance CSS animations](https://web.dev/articles/animations-guide): Reference source. ### Update JavaScript Arrays Without Mutating Shared State Canonical URL: https://ourjs.in/blog/immutable-array-updates/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Use deliberate copies for additions, removals, sorting and nested edits in frontend state. #### Know which value is shared An array can be referenced by a component, a cache and another variable at the same time. Changing it through one reference changes what every owner observes. Immutable updating means producing a new value for the changed result while preserving the previous value. It is especially useful when a UI framework compares references to decide whether something has changed. #### Add and remove with an explicit result For a task list, create an added list with a spread and the new task rather than pushing into the original state. Remove a task by filtering on its stable identifier. Keep identifier generation outside repeated render calculations. The important part is that a previous list remains a valid description of the earlier screen, which makes reasoning about undo and debugging easier. #### Replace the matching record Suppose task t-42 changes from open to done. Map over the list and return a new object for that identifier, while returning unchanged objects for other entries. Replacing only the array but mutating the existing task object still changes data shared with earlier snapshots. Copy each level on the path you modify, including a nested settings object if that is where the edit lives. #### Handle ordering without surprises Traditional sort and reverse methods modify their array. Copy before calling them when the input must remain intact, or use suitable copying alternatives supported by your browser target. Keep sorting rules separate from filtering rules so each operation can be inspected. For display-only ordering, derive the sorted list from source records instead of storing several competing versions of the same collection. #### Avoid copying everything blindly A complete deep clone on every keystroke can waste work and can mishandle values with special behavior. Prefer a targeted update that changes the necessary branches and preserves untouched references. If nested state becomes difficult to update safely, reconsider its structure. Storing records by identifier can make a single-row edit easier to express than repeatedly searching a deeply nested screen-shaped object. #### Verify previous snapshots stay unchanged Create a small input list, run an update, and inspect both the old and new values. Assert that the edited record differs, untouched records retain their identity where intended, and the previous record still has its original fields. Include a missing-identifier case and duplicate identifiers in review. These checks reveal data ownership mistakes that a visually correct first render can hide. Sources: - [MDN: Array.prototype.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map): Reference source. ### Updated CSS Missing in Production? Trace the Bytes Before Clearing Caches Canonical URL: https://ourjs.in/blog/debug-stale-css-deployment/ Author: Nayan Kumar. Published: 2026-10-26. Category: DevOps. Follow the stylesheet request through the browser, CDN and deployed artifact to identify which layer is serving old content. #### Start with a visible difference Choose one specific rule that changed, such as a button’s border radius, and locate the expected compiled declaration. A vague observation that the site looks old is difficult to investigate. Record the page URL, stylesheet URL and release identifier so the investigation compares actual files instead of relying on screenshots from different environments. #### Inspect the network response Open the stylesheet request in browser developer tools and read its response content. Check whether it contains the new rule, then inspect response headers and the source of the response. Temporarily disabling the browser cache is a diagnostic step, not proof that every upstream cache has been bypassed. A CDN or service worker can still influence the result. #### Split delivery from application If the response contains the new CSS but the page does not show it, inspect cascade order, selector matching, media queries and overridden declarations. If the response contains the old CSS, move toward the delivery pipeline. This split avoids spending time changing specificity when the browser never received the new file in the first place. #### Check a deployment example Suppose a build produces main.47.css, but production HTML still references main.36.css. The stylesheet server may be working correctly; the stale document is selecting the old asset. If production HTML references main.47.css and that file contains old bytes, inspect upload paths, origin contents and deployment artifacts. Each observation points to a different owner and correction. #### Look for inconsistent releases Repeat the request and compare release identifiers when multiple servers or regions are involved. One outdated instance can produce an intermittent problem that resembles random browser caching. Also examine service-worker behavior, reverse-proxy rules and CDN cache policies. Avoid invalidating everything repeatedly without first preserving evidence of which response was wrong and where it originated. #### Fix the process that allowed it Use content-versioned asset names, reliable artifact uploads and a deliberate HTML cache policy. Add a post-deployment check that verifies a known release marker and its referenced assets. Retest with an existing browser session as well as a fresh visit. The durable outcome is a release process that delivers consistent bytes, not an instruction asking every visitor to clear their cache. Sources: - [MDN: caching behavior](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching): Reference source. - [AWS: cache duration and invalidation](https://docs.aws.amazon.com/whitepapers/latest/build-static-websites-aws/controlling-how-long-amazon-s3-content-is-cached-by-amazon-cloudfront.html): Reference source. ### Use Content-Hashed Assets Without Caching HTML into a Stale Release Canonical URL: https://ourjs.in/blog/content-hashed-asset-caching/ Author: Nayan Kumar. Published: 2026-10-26. Category: Performance. Give immutable assets and frequently changing document pointers different cache policies. #### Separate files by responsibility An HTML document points to the JavaScript, CSS and images needed for a release. A fingerprinted asset has a URL tied to a particular content version. Those responsibilities suggest different caching behavior: a versioned file can be reused aggressively, while the document that selects current asset URLs must be able to learn about new releases. #### Make the filename meaningful If a stylesheet changes from site.a12.css to site.b34.css, the browser requests a new address rather than relying on an old cached response to update itself. The build must actually change the filename when the contents change. Appending an arbitrary constant version query that never advances provides a label, not a working content-versioning strategy. #### Walk through a release Imagine release A serves HTML referencing app.a1.js. Release B uploads app.b2.js and then publishes HTML referencing it. Keep app.a1.js available long enough for older documents or open sessions that still request it. Deleting all previous assets immediately can turn a well-cached old document into a broken interface, even when the newest homepage appears correct. #### Distinguish revalidation from prohibition Cache-Control directives describe storage and reuse rules with different meanings. For example, no-cache permits storage but requires validation before reuse, whereas no-store asks caches not to store the response. Choose settings based on the resource and privacy requirements rather than applying whichever directive sounds strongest. Inspect actual response headers because host defaults can override assumptions in application code. #### Avoid conflicting deployment practices Do not overwrite a supposedly immutable filename with different bytes. Avoid serving private user-specific responses under a shared public cache policy. Keep compression variants and relevant request headers accounted for in the cache configuration. A long max-age is useful only when the URL and deployment process support the promise that the cached representation remains appropriate. #### Measure the warm and cold paths Test a first visit, a repeat visit and an update from an older release. Check requested URLs, transferred bytes, validation responses and missing assets. Record which layer supplied each response: browser, CDN or origin. Caching success means both efficient reuse and reliable change propagation; a low transfer size is not a win if it keeps the user on obsolete code. Sources: - [MDN: HTTP caching](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching): Reference source. - [AWS: versioned file names](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/UpdatingExistingObjects.html): Reference source. ### Use Keyword Counts as an Editing Signal, Not a Content Strategy Canonical URL: https://ourjs.in/blog/content-quality-over-keyword-density/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Build useful technical articles around clear questions, accurate examples and maintained advice instead of repetition targets. #### Begin with a reader’s question A useful article has a job beyond containing a target phrase. Someone searching for a deployment fix needs a diagnostic path, not repeated statements that deployment is important. Write down the question, the intended audience and what a reader should be able to do afterward. That small editorial brief helps distinguish a worthwhile guide from a page created only to increase a site’s count. #### Use terminology naturally Technical terms matter because they identify real concepts, but repetition is not a substitute for explanation. A keyword-density counter can reveal a draft that overuses one phrase or never names its subject. It cannot determine whether the advice is correct, whether an example is reproducible, or whether the page deserves to appear for a particular query. #### Compare two article approaches Consider a guide about canonical tags. One draft repeats canonical URL in every paragraph while leaving the reader unsure what to inspect. Another shows a copied homepage canonical on a tool page, explains the mismatch, and provides a verification step. The second draft earns relevance through the problem it resolves rather than an artificial percentage of matching words. #### Add evidence and useful boundaries Explain assumptions, limitations and the environment in which instructions apply. Link to relevant primary documentation for details that change over time. Original examples and clear distinctions make a guide more useful than a lightly rewritten summary of another page. Avoid invented personal outcomes, unsupported rankings or client statistics as decoration; they undermine the trust the article is meant to build. #### Maintain the collection honestly A large journal needs a maintenance plan as well as a publishing plan. Update advice when APIs or hosting behavior change, consolidate overlapping pages, and remove promises that the underlying tools no longer support. Publication dates should reflect real publication, and modification dates should correspond to substantive revisions. More pages do not automatically create more useful answers. #### Review the finished experience Ask whether the title matches the body, whether the example works, whether a newcomer can follow the steps and whether the recommended next link adds value. Use counts to spot editorial issues, then make decisions with judgment. Search performance can inform later revisions, but a useful content strategy begins with solving readers’ problems accurately and consistently rather than chasing a preferred repetition ratio. Sources: - [Google: helpful, reliable content](https://developers.google.com/search/docs/fundamentals/creating-helpful-content): Reference source. ### Use Object-Fit to Crop Images Without Stretching Them Canonical URL: https://ourjs.in/blog/css-object-fit-cropping/ Author: Nayan Kumar. Published: 2026-10-26. Category: Images. Choose between cover and contain, preserve the important subject, and recognize when a new source crop is necessary. #### Give the image a defined frame Object-fit controls how replaced content such as an image fits its own content box. If the image simply uses its natural dimensions, there may be no visible fitting problem to solve. Start by deciding the display frame, such as a 16:10 project thumbnail or a square portrait, and then choose how the source should occupy it. #### Choose cover when cropping is acceptable Object-fit:cover preserves the source proportions while filling the frame, which can crop edges. That works well for many photographic thumbnails. It can be a poor choice for an interface screenshot when the cropped area contains navigation or important labels. A consistent card shape is not worth concealing the evidence a case study is trying to present. #### Choose contain when the whole image matters Object-fit:contain keeps the entire source visible inside the frame, leaving unused space when the aspect ratios differ. Give that space an intentional background. For example, a diagram can sit on a neutral panel without losing its annotations. Do not stretch the source with a fill behavior merely to avoid those margins. #### Place the focal point deliberately Object-position can move the fitted content within the frame. A portrait with a face near the top might need a different position from a centered product photograph. Test the chosen value at every supported frame ratio. A focal point that works in a wide card may still crop the subject awkwardly in a tall mobile presentation. #### Know when CSS is not enough A tightly cropped source cannot reveal details that were never included, and a screenshot may need a genuinely different composition for mobile. Export an alternate image when the design requires art direction. Keep the original available if a reader needs to inspect the full interface rather than inferring it from a small stylized preview. #### Verify both pixels and meaning Resize the layout while watching the important subject. Check that the image does not distort, key details remain visible and its alt text still matches the displayed information. Reserve the frame dimensions before loading. Then inspect the delivered file size: a good CSS crop does not reduce the number of source bytes downloaded. Sources: - [MDN: object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/object-fit): Reference source. ### Use Prefers-Color-Scheme Without Losing Explicit Theme Choices Canonical URL: https://ourjs.in/blog/prefers-color-scheme/ Author: Nayan Kumar. Published: 2026-10-26. Category: CSS. Build a theme preference order that respects the system and keeps forms, text and embedded surfaces consistent. #### Define the preference order A site can follow the operating system by default while allowing a person to choose a theme explicitly. Decide which choice wins before implementing the toggle. A practical order is an explicit saved preference, then the system preference, then the site’s default. Document that behavior so a later stylesheet does not quietly reverse it. #### Make each theme complete A light theme needs more than a pale page background. Inputs, borders, placeholder text, menus, code samples and focus indicators all need appropriate values. Use semantic custom properties for these responsibilities. For a product page, silver surfaces with plum text and gold accents can form a coherent light experience without inheriting dark header or footer panels. #### Use the media query as a baseline The prefers-color-scheme media feature lets CSS respond to a light or dark system preference. It can provide an initial theme without waiting for a component effect. If a manual choice is also supported, scope the system rule so that it does not override the explicit theme attribute after the person has selected a different mode. #### Consider browser-provided controls The color-scheme property tells the browser which schemes an element supports, affecting some native controls and other browser-rendered details. It does not recolor your custom components automatically. Match it to the actual page theme and inspect select menus, date fields and scrollbars rather than assuming all browser controls will follow custom variables. #### Handle persistence gracefully Saving a simple theme preference can make return visits more predictable, but storage access can fail. Catch that failure and let the switch still affect the current page. Avoid depending on user-agent detection or a large personalization script for a basic theme decision. Keep the saved value small and validate it before applying it. #### Check first paint and navigation Reload under each system preference and with each explicit setting. Watch for an unnecessary flash between themes, then navigate across routes and inspect the page chrome. Test screenshots and form fields separately. A successful theme system feels stable because the same preference is interpreted consistently before loading, after interaction and on the next page. Sources: - [MDN: prefers-color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/prefers-color-scheme): Reference source. ### Use Regular Expressions for Focused Input Validation Canonical URL: https://ourjs.in/blog/regex-input-validation/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Write small, testable patterns without treating a matching string as proof of a valid business operation. #### State the rule in ordinary language Before writing a pattern, describe exactly which strings should be accepted. For a project slug, the rule might be lowercase ASCII letters or digits, with single hyphens between nonempty groups. That is different from accepting every possible URL segment or transliterating names from every language. A narrow requirement makes the pattern easier to review and the error message more honest. #### Anchor a complete-value check If the whole input must follow the slug rule, anchor the pattern to the start and end. Otherwise a matching substring inside an invalid value may be enough for test to return true. Try an original example such as design-system-2, then contrast it with leading-hyphen and doubled-hyphen variants. Keep a small table of accepted and rejected examples beside the implementation. #### Avoid stateful flag surprises A regular expression with a global or sticky flag can update its lastIndex when tested repeatedly. That behavior is useful for scanning, but confusing for a reusable yes-or-no validator. For a whole-field validation rule, avoid unnecessary flags or manage the state explicitly. A pattern that appears to alternate between true and false for the same input deserves immediate investigation. #### Separate format from existence A matching email-shaped string does not prove that a mailbox exists, and an identifier with the right shape does not prove that the current person may access its record. Use a regex for its limited formatting role. Perform semantic checks, authorization and server-side validation at the boundaries where those rules can actually be enforced. #### Bound untrusted complexity Complex patterns with ambiguous nested repetition can take excessive time on certain inputs. Prefer clear structures and reasonable input limits. Do not run an arbitrary user-supplied pattern against a huge document on the main thread without considering cancellation and resource limits. A tool can explain this limitation and use a dedicated worker when its design requires isolation. #### Verify positive and negative cases Check empty input, surrounding spaces, unexpected line breaks, Unicode and the longest permitted value. Repeat validation several times to catch accidental lastIndex dependence. Also check the displayed explanation and whether it identifies how to fix the input. The goal is not the shortest possible pattern; it is a rule that remains understandable when the next edge case appears. Sources: - [MDN: RegExp.prototype.test](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test): Reference source. ### Use S3 as a Static Asset Origin with Explicit Access and Cache Decisions Canonical URL: https://ourjs.in/blog/aws-s3-static-assets/ Author: Nayan Kumar. Published: 2026-10-26. Category: AWS. Plan object paths, HTTPS delivery, access boundaries and metadata before treating an S3 bucket as a finished website host. #### Distinguish storage from delivery S3 stores objects, while the public website experience also needs correct routing, content types, TLS delivery and caching. A bucket containing index.html is only part of that system. Choose the intended hosting architecture before changing permissions. AWS offers several approaches, and a private bucket behind an appropriate delivery service has different requirements from an S3 website endpoint. #### Choose an appropriate public path S3 website endpoints have capabilities and limitations that differ from REST endpoints used as an origin behind CloudFront. In particular, HTTPS delivery and private-origin access require deliberate architecture choices. Consult the current AWS guidance rather than following a tutorial that begins by making all content public. The required access should follow the chosen delivery path, not precede it. #### Map a static-export example Imagine an export containing index.html, tools/index.html and tools/json-formatter/index.html. Uploading these objects preserves the file hierarchy, but the delivery layer still needs to resolve /tools/json-formatter/ as intended. Check directory-style paths, a direct asset URL and a missing path. A custom error response should not disguise every missing article as a successful homepage response. #### Set object metadata deliberately Content-Type influences how browsers interpret the response, while Cache-Control influences reuse. JavaScript, SVG, PNG and HTML need appropriate values. A filename extension alone does not guarantee that an upload command assigned the metadata you expect. Keep document cache policies distinct from versioned assets, and verify the final response through the public delivery domain rather than looking only at the object console. #### Keep deployments traceable Upload a complete, identified artifact and coordinate which document version references which assets. Do not remove previous fingerprinted files before older HTML and open sessions can finish using them. Prefer reproducible automation over an undocumented manual selection of files. Review required IAM permissions for the publishing task without granting broader bucket or account access simply to avoid a configuration error. #### Verify the full delivery chain Open the public HTTPS URL, inspect deep links and downloads, and check status codes and headers. Compare the deployed release marker with the intended artifact. If content is stale, distinguish the object at origin from the cached representation at the edge. A successful upload establishes storage; final browser checks establish whether the website’s actual delivery path works as intended. Sources: - [AWS: static website hosting with S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html): Reference source. ### Use unknown at Boundaries Instead of Spreading any Canonical URL: https://ourjs.in/blog/typescript-unknown-vs-any/ Author: Nayan Kumar. Published: 2026-10-26. Category: TypeScript. Validate external values and narrow errors so uncertainty stays at the edge of your application. #### Be honest about an unchecked value An API response, imported file or caught exception may not have the shape your component expects. The unknown type records that uncertainty and requires a check before meaningful use. The any type allows operations without those checks. Both can appear at integration boundaries, but letting any spread into ordinary application code removes useful feedback exactly where unfamiliar data is entering the system. #### Narrow a concrete import result Imagine a settings importer that receives unknown. First confirm the value is a non-null object, then verify the fields the feature requires. A name should be a string, enabled should be a boolean, and tags should be an array whose entries are supported strings. Return a new internal settings object after validation instead of asserting that the original value already satisfies the contract. #### Handle thrown values deliberately JavaScript code can throw values that are not Error instances. In a catch path, check whether the value is an Error before reading message. Provide a useful fallback for other cases, while keeping diagnostic handling separate from user-facing text. Do not cast every caught value to Error merely to satisfy the compiler; that assertion changes no runtime behavior. #### Keep checks close to the boundary Once external data has been validated, pass a trusted domain type through the rest of the feature. Rechecking unknown fields in every visual component makes rendering noisy and leaves uncertainty distributed across the codebase. A parser or adapter can explain both the accepted shape and how failures are reported, making future integration changes easier to isolate. #### Use assertions only with an explanation Some platform integrations require a type assertion because the compiler cannot express information you have already established. Keep those assertions narrow and document the evidence. An assertion should not be a shortcut around a missing runtime check for untrusted input. If the same assertion appears repeatedly, a typed wrapper or reusable validation function is often a clearer boundary. #### Verify malformed inputs as well as types Pass null, a primitive, an array, missing fields and fields with the wrong types into the adapter. Ensure the caller receives a specific failure rather than a later rendering exception. Run the compiler to catch unchecked property access. The goal is not eliminating every occurrence of any by force; it is preserving useful guarantees after the application has established what the data actually contains. Sources: - [TypeScript: functions and unknown](https://www.typescriptlang.org/docs/handbook/2/functions.html): Reference source. ### Verify Brotli and Gzip Delivery Instead of Assuming Files Are Compressed Canonical URL: https://ourjs.in/blog/compression-brotli-gzip/ Author: Nayan Kumar. Published: 2026-10-26. Category: Performance. Inspect negotiated encodings, response headers and transfer sizes when enabling text compression on a static site. #### Identify suitable resources HTML, CSS, JavaScript and other text-based formats often contain repeated patterns that compression can reduce. Already compressed media behaves differently, so applying another compression layer is not automatically useful. Start by measuring which resources contribute meaningful transferred bytes. Compression improves delivery of the bytes you keep; it does not remove unnecessary code or make a large application architecture simpler. #### Understand the request and response A browser advertises supported encodings through the request, and the server or CDN selects an appropriate representation. Content-Encoding describes the encoding applied to the response body. It is distinct from Content-Type, which describes the resource’s media type. Mixing these roles can produce incorrect metadata and a file that downloads but cannot be interpreted properly. #### Test a concrete stylesheet Suppose a generated stylesheet is 90 KB before transport compression. Request it through the public domain and compare the transferred size with the decoded resource size in developer tools. Confirm whether the response indicates br or gzip. The example does not imply a fixed savings percentage; results depend on the file contents and encoding configuration. #### Check variants and hosting behavior The cache and origin must handle encoding variants correctly so a client receives a decodable response. When serving precompressed files, verify that the host maps requests to the correct representation and headers. Uploading a .br file beside a stylesheet does not ensure that a generic static server will automatically negotiate and serve it. #### Avoid misleading local comparisons A development server, local file preview and production CDN may have different compression behavior. Measure the final delivery path and note whether the request is a cold download or a cached reuse. Compare equivalent builds and resources. A smaller source file, a compressed response and a cache hit are three different reasons for low transfer activity, with different implications for optimization. #### Keep the verification repeatable Record a representative HTML, CSS and JavaScript URL along with their encoding, media type and transfer result. Test a supported encoded request and a request without that encoding where practical. Recheck after host or CDN configuration changes. If an asset still dominates loading, investigate its necessity and request timing rather than treating transport compression as the only remaining performance lever. Sources: - [MDN: Content-Encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Encoding): Reference source. ### When to Use Map and Set in Frontend JavaScript Canonical URL: https://ourjs.in/blog/javascript-map-set-use-cases/ Author: Nayan Kumar. Published: 2026-10-26. Category: JavaScript. Choose collections for lookups and uniqueness without confusing object identity with value equality. #### Match the collection to the question Arrays describe ordered sequences, objects describe named properties, Maps associate keys with values, and Sets track unique values. Start by writing the question your code asks most often. A screen that repeatedly checks whether an identifier is selected has different needs from one that simply renders ten items in order. Choosing the data shape well often removes unnecessary loops. #### Use a Map for explicit lookup ownership Imagine a table whose row details arrive separately from its visible order. A Map keyed by row identifier can associate each identifier with its latest record, while an array controls display order. Looking up row-17 then communicates intent directly. Keep replacement and deletion behavior explicit, especially when the visible order still contains an identifier whose data has been removed. #### Use a Set for membership A selectedIds Set makes membership checks readable and prevents the same identifier from being selected twice. For a filter menu, deduplicate primitive category strings with a Set, then create an array for rendering. Decide whether capitalization and surrounding whitespace should be normalized first; uniqueness follows the actual stored values, not the human meaning of a label. #### Understand object identity Two separately created objects containing the same fields are still different object references. Adding both to a Set does not deduplicate them by their field values. For imported records, use a meaningful primitive key, such as a normalized external identifier, when that matches the business rule. Do not invent a JSON-stringification equality rule without considering property ordering and unsupported values. #### Preserve state update expectations Map.set, Set.add and their deletion methods mutate the collection. When storing one in React state, create a new collection before changing it so the reference represents a new state value. Also remember that JSON does not automatically serialize these structures into a useful record list. Choose an explicit transport format instead of assuming a browser collection is already an API contract. #### Check boundaries with examples Test repeated strings, differently cased labels, numeric versus string identifiers, and two equivalent-looking objects. Verify that removing a row also reconciles selection and displayed counts. For serialization, round-trip the chosen array or object representation. The best collection is the one that makes these boundary rules visible to the next person maintaining the feature. Sources: - [MDN: Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map): Reference source. ### Write Form Validation Errors That Help People Recover Canonical URL: https://ourjs.in/blog/form-validation-error-messages/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Turn invalid form states into specific, accessible instructions instead of generic red outlines. #### Describe the correction An error message should explain what to do next. Invalid value tells someone almost nothing. Enter an email address such as name@example.com gives a concrete path forward. Keep the language tied to the field and the real requirement, without blaming the user or inventing restrictions that the application does not actually enforce. #### Start with HTML constraints Required fields, appropriate input types and sensible numeric limits can prevent straightforward mistakes. The browser’s constraint validation is a useful baseline. Custom validation should address actual application rules or improve the message experience. A decorative JavaScript layer that duplicates native checks can introduce inconsistent states unless both systems are deliberately coordinated. #### Choose when to interrupt A form that reports errors after every keystroke can be exhausting. A reasonable pattern is to validate on submission, then update a field’s existing error as the user corrects it. For example, do not call an unfinished email invalid while the person is still typing its domain unless there is a clear usability reason. #### Connect feedback to the field Give each message an id and reference it from the relevant control with aria-describedby. Set aria-invalid when the value has failed validation. Preserve visible text alongside any color or icon, because a red border is not a complete explanation. If an error disappears, update its associated state and description rather than leaving stale announcements behind. #### Handle multiple errors coherently For a longer form, a summary near the top can list the fields that need attention and link to them. Move focus deliberately after a failed submission so the reader can discover that summary. Keep entered values in place. Requiring someone to reconstruct an entire project inquiry after one invalid field turns a small mistake into unnecessary work. #### Verify the recovery journey Submit an empty form, then one with a malformed email, then a valid example. Check that the first error is discoverable with a keyboard and that correcting it clears the message. Client-side validation is still a convenience, not a security boundary: any server receiving submissions must validate its input independently. Sources: - [MDN: constraint validation](https://developer.mozilla.org/en-US/docs/Web/HTML/Guides/Constraint_validation): Reference source. ### Write Image Alt Text Around Purpose, Not Keywords Canonical URL: https://ourjs.in/blog/image-alt-text/ Author: Nayan Kumar. Published: 2026-10-26. Category: Accessibility. Describe the information an image contributes and avoid repeating nearby text or decorating every picture with a caption. #### Ask what would be missing Imagine removing the image from the page. What information would a reader lose? That question is a better starting point than naming every visible object. A project screenshot might demonstrate a dashboard’s filter layout, while an abstract shape behind the title contributes no information at all. Their alternative text should not be treated the same way. #### Describe informative images concisely A useful description explains the relevant content in context. On a case study about a responsive checkout, an image might be described as Mobile checkout with delivery details above the payment summary. The goal is not an exhaustive visual inventory. Focus on the detail the surrounding discussion expects the reader to notice. #### Give decorative images an empty alternative For an img that is purely decorative, an empty alt attribute allows assistive technology to skip it. Omitting alt is a different choice and can expose an unhelpful filename in some contexts. CSS background decoration usually does not need a text alternative, but it must not carry information that is otherwise absent from the page. #### Consider the surrounding link When an image is the only content of a link, its alternative needs to communicate the link’s purpose. If a project card already includes a clear text title in the same link, repeating that entire title as image alt may create a redundant name. Review the accessible name of the complete interactive element, not the image in isolation. #### Handle charts and text-heavy images differently A chart may need a concise image alternative plus a nearby explanation or data table. A screenshot containing important instructions should not be the only place those instructions appear. Where possible, use real text for headings, labels and explanatory content. A very long alt attribute is not an effective substitute for a structured explanation. #### Review without looking at the picture Read the title, image alternative and nearby paragraph aloud as one sequence. Remove duplicated information and irrelevant phrases. Check that filenames, target keywords and generic descriptions such as beautiful image have not replaced useful meaning. Alt text succeeds when someone can understand the image’s contribution to the page without having to see it. Sources: - [W3C WAI: image alt decision tree](https://www.w3.org/WAI/tutorials/images/decision-tree/): Reference source. ### Write Meta Descriptions Around the Reader’s Next Decision Canonical URL: https://ourjs.in/blog/meta-description-writing/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Turn a page summary into useful preview copy while keeping expectations about search snippets realistic. #### Identify the decision being made A person scanning results wants to know whether a page will answer a question or finish a task. Write down that decision in plain language before drafting the description. For a browser image tool, relevant details might be supported formats, local processing and the available output. Generic enthusiasm tells the reader much less. #### Describe real capabilities A description should summarize what the page demonstrably provides. If a tool exports only WebP, do not promise every image format. If a contact form opens an email draft, do not describe it as an instant submission service. Accurate limitations often make copy more useful because they help unsuitable visitors avoid a wasted trip. #### Rewrite an example Consider this draft for a JSON formatter: The best amazing free developer platform for all your needs. Replace it with Format, validate and minify JSON in your browser, then copy the result. No account required. The revision names the task, explains the output and includes a concrete access detail without inventing a claim of superiority. #### Keep pages distinguishable Write separate descriptions for a portfolio overview, a project case study and an article. Sharing a brand does not make their value identical. For a large collection, generate drafts from reliable structured fields and review exceptions. A template that repeats the same sentence with only a noun changed can conceal meaningful differences in how the pages work. #### Treat previews as approximations A search-style preview helps assess wording and hierarchy, but it cannot dictate the text a search engine displays. The query and page content can influence the resulting snippet. Character counts are useful for spotting verbosity, not for promising exact truncation. Make the opening words informative and let the visible page support the description. #### Review during content maintenance When a feature or article changes, check the description alongside it. Remove unsupported promises, obsolete format lists and dates that no longer add value. Read the draft aloud: can a new visitor explain what happens after clicking? Finally inspect the generated HTML so an inherited layout description has not replaced the page-specific value you intended. Sources: - [Google: search snippets and meta descriptions](https://developers.google.com/search/docs/appearance/snippet): Reference source. ### Write React Effects with Symmetrical Cleanup Canonical URL: https://ourjs.in/blog/react-effect-cleanup/ Author: Nayan Kumar. Published: 2026-10-26. Category: React. Manage event listeners, timers, observers and requests as owned resources rather than one-time setup rituals. #### Describe the external system An effect is useful when a component must synchronize with something outside React rendering, such as a browser event subscription or a third-party widget. Start by naming that system and the values that configure it. If the code only transforms props into display data, an effect may add an unnecessary second update instead of solving an external synchronization problem. #### Pair setup with its inverse A resize listener should be removed, an interval cleared and an observer disconnected when the owning synchronization ends. Return a cleanup function that can refer to the exact resource created by that effect invocation. Keeping setup and cleanup adjacent makes ownership easier to review than storing unrelated global handles that several components can overwrite. #### Use a concrete subscription example Suppose a component listens for document visibility changes to pause a preview. Define the handler within the effect, attach it to the relevant event and remove that same handler in cleanup. If a new configuration requires a new handler, React can clean up the previous subscription before establishing the next one. The source should explain this relationship without relying on a mount-only mental model. #### Treat development repetition as a useful check React development checks can exercise a setup, cleanup and setup sequence to reveal lifecycle mistakes. A correct subscription should tolerate that sequence without leaving duplicate listeners or broken state. Avoid suppressing the behavior with a ref that merely prevents the second setup. That workaround can hide the missing inverse operation and leave real navigation or configuration changes unreliable. #### Handle asynchronous completion ownership When an effect starts a request, cleanup should cancel it where supported or mark its result irrelevant. Otherwise a response associated with an old query can update the current screen. Dependencies describe which values configure synchronization; omitting them to reduce reruns can preserve stale closures. Restructure the effect around the true external relationship instead of fighting the dependency list. #### Verify repeated lifecycle transitions Open and close the feature repeatedly, change its configuration and navigate away while work is pending. Confirm that only one active subscription remains and that outdated results are ignored. Check cleanup after an error as well as normal completion. A resource can appear harmless during one render yet accumulate during ordinary navigation, so repeated use is the meaningful test. Sources: - [React: synchronizing with effects](https://react.dev/learn/synchronizing-with-effects): Reference source. ### Write Unique Page Titles That Explain the Page Before the Brand Canonical URL: https://ourjs.in/blog/unique-page-titles/ Author: Nayan Kumar. Published: 2026-10-26. Category: SEO. Build useful title patterns for tools, articles and portfolio pages without repeating the same phrase everywhere. #### Name the specific destination A title should help someone distinguish one page from neighboring results and open browser tabs. Start by naming the subject or task the page actually covers. A portfolio project, a JSON formatter and a contact page serve different needs, so their titles should not all lead with an identical list of services. #### Use a restrained title pattern A useful site convention is a descriptive page title followed by a short identity, such as JSON Formatter — Format and Validate JSON | Nayan Kumar. The descriptive part carries the task; the suffix supplies continuity. Do not repeat the suffix inside the page title and again through a layout template, producing two copies of the same brand. #### Test competing drafts For a hypothetical article about stale CSS, compare Web Development Tips with Why Your Updated CSS Is Missing After Deployment. The second draft tells the reader which problem the article solves. If the body instead covers only browser cache, narrow the title accordingly. Specificity is useful only when the content supports the expectation it creates. #### Align the visible introduction The main heading can have a different editorial rhythm, but it should describe the same topic as the title. An article whose title promises a deployment checklist and whose first screen discusses unrelated animation trends creates unnecessary confusion. Review title, heading and opening paragraph together rather than optimizing each field in isolation. #### Avoid mechanical length rules A title preview is an editing aid, not a guarantee of search appearance. Display depends on the available space and the search system may choose different text. Remove redundant words because they obscure meaning, not because a counter demands a particular number. Never pad a short, clear title with geographic or service terms unrelated to the page. #### Inspect the exported result After building, check the actual title element on several page types and find duplicates programmatically. Include missing routes and pagination in the sample. Change one title when the underlying page changes substantially, then allow time for search systems to revisit it. Judge whether the new wording accurately describes the page before interpreting traffic changes. Sources: - [Google: title links](https://developers.google.com/search/docs/appearance/title-link): Reference source. ### How to Compress Images Without Losing Visible Quality Canonical URL: https://ourjs.in/blog/compress-images-without-losing-quality/ Author: Nayan Kumar. Published: 2026-10-20. Category: Image Optimization. Learn practical techniques for smaller images, faster pages and better Core Web Vitals. #### Why image size matters Images often represent the largest share of bytes on a page. Reducing file size can improve load times, particularly on slower mobile connections. #### Choose the right format Use JPEG for photographs, PNG when transparency or lossless precision is essential, and WebP for broad modern-browser support. Compare output visually before replacing originals. #### Choose a sensible quality level For photographic JPEG and WebP images, begin around 75–85 percent quality, then inspect fine details and gradients. The ideal value depends on the source. #### Resize before compressing Do not ship a 4000-pixel-wide image to a 400-pixel-wide card. Generate appropriately sized images and use responsive image markup. #### Measure the impact Test with PageSpeed Insights and inspect Largest Contentful Paint. Compression helps, but caching, dimensions, lazy loading and network delivery also matter. ### Next.js SEO Checklist for Fast, Discoverable Websites Canonical URL: https://ourjs.in/blog/nextjs-seo-checklist/ Author: Nayan Kumar. Published: 2026-10-18. Category: Next.js. A practical checklist for metadata, semantic HTML, sitemaps and crawlable pages. #### Build pages search engines can access Use meaningful HTML headings, visible page content and stable links. Static rendering is an effective option for public content pages. #### Write unique metadata Give every page a distinct title, description and canonical URL. Match search intent instead of repeating the same keywords everywhere. #### Add a sitemap and robots.txt List important canonical pages in your XML sitemap and verify that robots.txt does not block them. #### Use structured data carefully JSON-LD can describe an organization, article or software tool. Only mark up information that accurately reflects the page. #### Monitor real performance Verify your domain in Google Search Console, submit your sitemap and review indexing, queries and Core Web Vitals over time. ### WebP vs JPEG vs PNG: Which Image Format Should You Use? Canonical URL: https://ourjs.in/blog/webp-vs-jpeg-vs-png/ Author: Nayan Kumar. Published: 2026-10-15. Category: Web Performance. Understand the tradeoffs between file size, transparency, compatibility and quality. #### JPEG for photography JPEG is a common choice for photographs where transparency is unnecessary. Its lossy compression can reduce file size significantly. #### PNG for precise graphics PNG preserves exact pixel data and supports transparency, but photo files can become large. #### WebP for modern delivery WebP supports lossy and lossless compression as well as transparency, often at smaller file sizes than older formats. #### Test actual files Format performance depends on the image. Compare representative images rather than assuming one format always wins. ### Core Web Vitals: A Practical Guide for Small Business Websites Canonical URL: https://ourjs.in/blog/core-web-vitals-guide/ Author: Nayan Kumar. Published: 2026-10-10. Category: SEO. Improve LCP, INP and CLS with targeted frontend changes. #### Largest Contentful Paint Prioritize your main above-the-fold content, compress hero assets and avoid render-blocking dependencies. #### Interaction to Next Paint Reduce heavy JavaScript and long main-thread tasks so user interactions feel responsive. #### Cumulative Layout Shift Reserve space for images and embeds and avoid injecting content above existing elements. #### Prioritize measured issues Use field data when available and compare before-and-after measurements rather than chasing synthetic scores alone.