AI 资讯
The browser only talks to one server — composing Marko, React, and Riot into one hotel page
You open a hotel page. It looks like one product: a search grid, a featured stay, local highlights, reviews, a sticky trip summary. Under the hood it is eight HTTP servers and three UI runtimes . That is the experiment behind HarborStay , a demo booking app I built to answer a stubborn question: Can independent teams ship independent UI, in independent frameworks, and still give the browser a single, paint-ready HTML page? The punchline: yes — if the shell never imports a component. It only fetches HTML. The one rule The browser never talks to a fragment. It talks to the composer on port 3100 . The composer owns routes, layout, and the booking flow. Everything else is a fragment server that returns a chunk of HTML. flowchart LR Browser["Browser"] --> Composer["Composer :3100"] subgraph fragments["Fragment servers"] Nav["Navigation Marko :3101"] Search["Hotel search Marko :3102"] Details["Hotel details Marko :3103"] Reviews["Reviews Marko :3104"] Recs["Recommendations Marko :3105"] Highlights["Local highlights React :3106"] Disco["Experiences discovery Riot :3107"] Itin["Experiences itinerary Riot :3108"] end Composer --> Nav Composer --> Search Composer --> Details Composer --> Reviews Composer --> Recs Composer --> Highlights Composer --> Disco Composer --> Itin Composer --> CDN["CDN :3200"] This is the opposite of the usual microfrontend story (Module Federation, shared React, a host that import() s widgets). HarborStay is HTML composition . The shell does not know whether a fragment was rendered by Marko, React, or a hand-rolled Riot string. It only knows a URL. That one constraint buys a lot: Fragment teams can pick a runtime without asking the shell. A fragment outage becomes a fallback box, not a blank page. You can deploy search without redeploying reviews. It also forces honesty. If two fragments need to share a Redux store, the architecture is already leaking. What the user actually sees HarborStay models a small premium catalog: Harbor View Lodge in Lisbon
AI 资讯
How to take over a design built in Figma Make and develop it with Claude Code
From February to April 2026, I launched four web apps, each starting from a code bundle that Figma Make (Figma's AI feature that generates a working front-end code bundle from a design) had spat out: a beauty-curation site, a gift-record app, a plush-toy album, and a UI mock for an AI development tool. Every one of them starts its repository in a state where "the look is already finished." In this article I look back — from the actual config files and commit history — at what I did to get those generated outputs into a state where I could take over development in Claude Code (Anthropic's CLI coding agent) and start working on them, and at how far each of the four repositories progressed or stalled. The starting point: what shape does a Figma Make output come in? A Figma Make export runs as-is with npm run dev . The README tells the story. # Beauty Information Curation Site This is a code bundle for Beauty Information Curation Site. The original project is available at https://www.figma.com/design/ <id> /... ## Running the code Run `npm i` to install the dependencies. Run `npm run dev` to start the development server. A README that says "the original lives in Figma." That symbolizes the character of the output: the code is a projection of the Figma design, and the code is not the source of truth. On top of that, if you look at package.json , every dependency is exact-pinned. { "dependencies" : { "next" : "15.3.4" , "react" : "19.1.0" , "react-dom" : "19.1.0" , "lucide-react" : "0.487.0" , "motion" : "12.23.24" , "tailwind-merge" : "3.2.0" } } Fixed versions with no ^ . As a snapshot of the moment it was generated, it is highly reproducible, but leave it as-is and it grows stale with no one ever updating it. There is no data layer either. The screens are pretty, but behind them everything is mock data — no persistence, no authentication. "It runs, but there is no foundation to grow it on" — this was the common starting point across all four repositories. [画像: The READ
AI 资讯
From Contract Boundary to Error Boundary: Structuring API Error Handling in a TypeScript Frontend
In a previous post , I covered why TypeScript types alone can't protect you from a backend that returns something you didn't expect, and how to build a small apiRequest boundary that validates both the outgoing request and the incoming response against Zod-style schemas before your application ever touches the data. That post answered one question: Is this data actually shaped the way I think it is? It left another question open: When the answer is no, or when the request fails for a completely different reason (like a timeout or a dropped connection), what does the rest of the app do with that failure? In practice, "the rest of the app" usually does something different depending on who's writing it: One component checks error.response?.status directly. Another checks error.code === "ECONNABORTED" . A form manually digs through the error to find field-level messages. A toast just displays whatever string happens to be on error.message . The app works, but every layer speaks a different error dialect. This post is Part 2: it takes the validation boundary from Part 1 and builds the missing piece on top of it, a single, normalized ApiError shape that every layer of the app can speak, plus the logging, messaging, and form-mapping that make it actually usable. Quick Recap: The Validation Boundary From Part 1, the apiRequest wrapper validates request payloads and response bodies against schemas, and throws one of two typed errors when something doesn't match the contract: export class ApiRequestValidationError extends Error { constructor ( public readonly url : string , public override readonly cause : unknown ) { super ( `API request input does not match the contract for ${ url } .` ); this . name = " ApiRequestValidationError " ; } } export class ApiResponseValidationError extends Error { constructor ( public readonly url : string , public override readonly cause : unknown ) { super ( `API response does not match the contract for ${ url } .` ); this . name = " ApiRespon
开发者
React & Frontend Engineer Career Path — Beyond Knowing React (2026)
Knowing React Is Not the Same as Being a Frontend Engineer A huge number of self-taught developers can build a React component, wire up useState , and fetch data with useEffect . A much smaller number can build a frontend that stays fast as it grows, handles real error states gracefully, and doesn't quietly re-render half the page every time a user types a letter. That gap — between "I can use React" and "I can build a production frontend" — is where a lot of otherwise-promising candidates get stuck. It's not usually a knowledge problem about React's API. It's a gap in the surrounding skills: state architecture, performance, accessibility, and the unglamorous parts of frontend work that tutorials rarely cover in depth. This guide lays out a realistic path from "knows React" to genuinely job-ready frontend engineer, focused on the specific gaps that show up in real interviews and real codebases. This post originally appeared on the Ciphemic Academia blog . What "Frontend Engineer" Actually Requires Beyond React Basics The role is broader than component-building, and being explicit about what it covers helps target the right skills: State management at scale — not just useState in one component, but how state should flow through an application with many interconnecting pieces Performance — understanding re-renders, memoization, and why a frontend that works fine with test data can slow down badly with real data volume Accessibility and semantic HTML — building interfaces that actually work for everyone, not just visually API integration done properly — loading states, error states, race conditions, not just the happy-path fetch call Testing — component and integration tests that catch real regressions, not just tests that exist to say tests exist A typical React tutorial project touches the first item briefly and skips most of the rest. That's exactly why a portfolio built entirely from tutorial-style projects tends to fall short in real interviews. Step 1: Confirm Ja
AI 资讯
Migrating a Headless CMS? Your Frontend Shouldn't Know About It
A headless CMS migration often sounds simple: Contentful → Strapi Move the content, update the API calls, fix a few components, and you're done. Except... you're usually not. The hardest part of a headless CMS migration isn't moving the content. It's managing the contract between the CMS and the frontend . And if your React or Next.js application is tightly coupled to the CMS response structure, changing the CMS can turn into a much bigger project than expected. The problem Imagine your frontend directly consumes Contentful responses: const ProductCard = ({ product }) => { return ( < article > < h2 > { product . fields . title } < /h2 > < p > { product . fields . description } < /p > < img src = { product . fields . image . fields . file . url } / > < /article > ); }; It works. Until you migrate to Strapi. Now the response might look completely different: product . title product . description product . image . url Suddenly, the frontend needs to understand both CMS structures. And this problem isn't limited to simple fields. Things become much more complicated with: Rich text Media and assets References Nested relations Localization Draft/preview content SEO metadata Dynamic components Pagination GraphQL vs REST Different content modeling approaches The architecture I prefer Instead of allowing React components to consume the CMS directly, introduce a layer between the CMS and the application. ┌───────────────┐ │ Strapi │ └───────┬───────┘ │ ▼ ┌───────────────┐ │ CMS Adapter │ └───────┬───────┘ │ ▼ ┌───────────────┐ │ Domain Model │ └───────┬───────┘ │ ▼ ┌───────────────┐ │ React / Next │ └───────────────┘ The frontend doesn't need to know whether the data came from Strapi, Contentful, Shopify, WordPress, or something else. It just receives the data it needs. For example: type Product = { id : string ; title : string ; description : string ; image : { url : string ; alt : string ; }; }; The CMS adapter is responsible for transforming the CMS response into this model
AI 资讯
How Does a Website Become Fast?
You open a website. A blank screen appears. You wait. Then finally, the page loads. But what actually happened during those few seconds? Why does one website feel almost instant while another feels painfully slow? It isn't just about writing “better code.” Website performance is the result of many things working together: DNS + networking + servers + HTML + CSS + JavaScript + images + caching + browser rendering And most performance problems come down to two simple questions: What is the browser waiting for? What is the browser doing unnecessarily? Let's break it down. What Actually Happens When You Open a Website? Suppose you enter: https://example.com Your browser has quite a journey ahead. A simplified version looks like this: URL ↓ DNS Lookup ↓ Connect to Server ↓ HTTP Request ↓ Receive Response ↓ Parse HTML ↓ Download CSS / JS / Images ↓ Build DOM + CSSOM ↓ Layout ↓ Paint ↓ Interactive Page Every step takes time. So the goal of performance optimization isn't simply: “Make the code faster.” It's: Reduce unnecessary waiting and unnecessary work. 1. Send Less Data Imagine your homepage downloads: HTML 250 KB CSS 400 KB JavaScript 4 MB Images 8 MB Fonts 2 MB That's a lot of data just to display a page. Now imagine: HTML 80 KB CSS 100 KB JavaScript 500 KB Images 1 MB Fonts 300 KB The browser has significantly less to download and process. This is why techniques such as: Compression Code splitting Lazy loading Responsive images Removing unused dependencies can have a huge impact. A simple rule: If the user doesn't need it yet, don't make them download it yet. 2. Images Can Be Your Biggest Bottleneck You can optimize your JavaScript perfectly... …and still have a slow website because of images. Consider a: 5 MB hero image That's potentially more expensive than many of your JavaScript files combined. Instead of sending a huge original image: <img src= "hero-original.jpg" /> serve an appropriately sized and compressed image. Modern formats such as: WebP AVIF can reduce
AI 资讯
How to Style an HTML : A Clean, Copy-Paste CSS Pattern
Most browsers render an HTML <hr> as a horizontal rule, but the default styling is not always what you want in a real interface. A common first attempt is to change height or color and move on. That can leave the browser's default border in place, which is why a divider may look thicker, doubled, or different from the design you expected. Here is a small, reusable pattern that makes the result predictable. Start with a stable divider class Add this HTML wherever a thematic break between sections makes sense: <hr class= "section-divider" > Then add this CSS: hr .section-divider { border : 0 ; border-top : 2px dashed #ca8a04 ; width : 60% ; max-width : 42rem ; margin : 2rem auto ; } This creates a centered, dashed divider that stays readable on both narrow and wide layouts. Why this pattern works There are four important choices in that snippet: border: 0 removes the browser's default border before you add your own style. border-top gives you one visible line to control. width and max-width keep the divider from becoming excessively long. margin: 2rem auto adds vertical breathing room and centers the element. The hr element is also semantic. It represents a thematic break in content, such as a shift from one topic to another. That makes it a better choice than a random empty div when the line actually separates ideas. Three useful variations Once the base pattern is in place, changing the appearance is straightforward. A quiet solid divider Use this when the line should support the layout without attracting attention: hr .section-divider { border : 0 ; border-top : 1px solid #cbd5e1 ; width : 100% ; margin : 1.5rem 0 ; } A dotted divider A dotted rule works well for lightweight notes, forms, or playful interfaces: hr .section-divider { border : 0 ; border-top : 2px dotted #94a3b8 ; width : 50% ; margin : 2rem auto ; } A stronger double divider For an editorial section break, use a double border with enough thickness for the two lines to remain visible: hr .section-div
开发者
Small update since this post was published: added dark theme, improved tooltips, more optimization for phones, "Share" button, puzzle intro on first visit, and PWA support, so the app installs like a regular app. Still open to feedback! I'd really apprecia
I created an interactive version of the Zebra puzzle (Einstein's riddle) - I would appreciate your feedback! Andrii Andrii Andrii Follow Aug 24 I created an interactive version of the Zebra puzzle (Einstein's riddle) - I would appreciate your feedback! # showdev # frontend # webdev 3 comments 2 min read
AI 资讯
Run Vue Component Tests Where Vue Runs: The Browser
A Vue component's job is to produce DOM in a browser. Most component tests ask it to do that somewhere else: in Node, against a DOM that jsdom simulates. That has been the default since npm create vue@latest started offering Vitest with jsdom, and for plenty of tests it is the right trade. It does set a ceiling on what a green test proves, though. Nothing is ever drawn. Your CSS never runs and nothing has a size or a position, so a component can pass every assertion in the file and still be broken on screen. I co-maintain twd-js , which runs tests inside your actual dev server, in a sidebar, next to the app. It was built for flow testing: visit a route, click through the app, assert on what the user sees. Component testing was the thing it did not do. Then I tried calling render() from @testing-library/vue inside a TWD test. import { afterEach , describe , it } from " twd-js/runner " ; import { twd , userEvent } from " twd-js " ; import { render , screen , cleanup } from " @testing-library/vue " ; import HomeView from " ../../views/HomeView.vue " ; import { componentHost , restorePage } from " ../support/componentHost " ; describe ( " HomeView component " , () => { afterEach (() => { cleanup (); restorePage (); }); it ( " increments the counter on click " , async () => { // componentHost() is a blank div on an empty page. More on it below. render ( HomeView , { container : componentHost () }); const button = await screen . findByTestId ( " counter-button " ); twd . should ( button , " contain.text " , " Count is 0 " ); await userEvent . click ( button ); twd . should ( button , " contain.text " , " Count is 1 " ); }); }); Nothing broke. The component mounts into the page, the sidebar shows it running, and reactivity does what reactivity does, in a browser, against a DOM nobody had to simulate. Why this works at all Vue Testing Library is a thin layer. render() mounts your component with @vue/test-utils and binds @testing-library/dom queries to the result. Neither of
AI 资讯
Ownership, and Making This Template Your Own (Part 5)
Part 4 covered how this platform actually ships — scaffolding, CI/CD, and the two deployment shapes. This closing part is the two things every one of the last four parts has assumed: who actually owns each piece of this, and what it takes to make this whole template yours. Who owns what Every piece of this platform belongs to exactly one team, and that split is what makes independent deploys survive contact with a real organization, not just a single-team demo: Piece Owned by Depends on Host / Shell Platform team Store, Components, the manifest, the identity provider Components MFE Platform / design-systems team Nothing (a leaf) Store MFE Platform team The identity provider Utilities MFE Platform team Nothing (a leaf) Domain MFE (×N) Domain team Components, Store, Utilities only Manifest Registry Platform team Nothing Identity provider(s) Outside the platform — whichever the deployment configures — Backend / BFF Domain team, or a shared gateway (Part 2) Each team's own data The rule underneath the table: domain teams never import from each other, only from the shared platform layer. That keeps the dependency graph a strict two-level tree — Host → platform layer → domain leaves — instead of a mesh, which is what keeps independent deployability tractable once there's more than a handful of domain teams. It's the same rule that made every part of this series possible to write in isolation: Part 3's auth flow doesn't need to know Part 4's deploy pipeline exists, and neither needs to know how many domain teams there eventually are. Making this template your own Everything organization-specific in this platform — branding, which identity provider(s) it trusts, where the manifest lives — has lived in one file across this entire series, on purpose: // platform.config.json { "orgName" : "acme-corp" , "branding" : { "primaryColor" : "#0B5FFF" , "logoUrl" : "..." }, "idp" : { "issuers" : [ { "id" : "primary" , "issuer" : "https://issuer.example.com" , "clientId" : "..." , "def
AI 资讯
Why Module Federation — Building an Enterprise MFE Platform (Part 1)
This series walks through an actual enterprise microfrontend platform, end to end: one Host shell, three shared platform microfrontends, a manifest-driven mechanism for mounting any number of independently-owned domain microfrontends, a full OIDC auth flow, and a CI/CD pipeline. Every code snippet in this series is real and traceable to the actual boilerplate it's built from, on GitHub . Part 1 is the decision everything else in this series depends on: why Module Federation , and not one of the two other credible options. The one requirement that rules everything else out Strip away the buzzwords, and an "enterprise microfrontend platform" only has to guarantee one thing: a team ships a change to their part of the app without anyone else redeploying anything. Not "in theory, with enough coordination" — actually, mechanically, true. If shipping one team's bug fix requires a platform team to cut a release, this isn't microfrontends — it's a monolith with extra steps. That single requirement rules out more than it looks like it should. It rules out compiling every team's code into one shared build (that's just a single-page app with more steps). And it rules out anything where the Host app needs to know, at its own build time, which teams' pages exist and which version of each — because "known when the Host was built" and "deployed independently of the Host" are opposites. The decision Use Webpack 5 Module Federation , in runtime-composition mode, as the platform's way of putting every team's page together into one app: The Host ships with an empty list of remote apps built in. Instead, it looks up every team's page from a small list — a manifest — that it fetches fresh every time the app loads. React, the shared state layer, and the shared design system are all declared as singletons : every team's page gets the exact same running instance of each, not its own separate copy. "Deploying" a team's page means adding or updating one entry in that manifest. The Host itself
AI 资讯
Durante meus estudos em ADS, comecei a aprender HTML, CSS e Python. Tenho maior interesse por HTML e CSS, principalmente pela criação de sites e interfaces. Meu principal desafio foi entender como HTML e CSS trabalham juntos e desenvolver a lógica de pro
AI 资讯
Svelte/SvelteKit Forms: The Fastest Path From ` ` to Inbox
Svelte/SvelteKit Forms: The Fastest Path From <form> to Inbox with onsubmit.dev (form backend) SvelteKit makes forms pleasant to build, but a contact form still needs somewhere to send its data. If all you want is “visitor fills out <form> → message arrives in my inbox,” building and operating another server-side handler can feel disproportionate. onsubmit.dev (form backend) provides a hosted form endpoint for that job, and its Svelte integration can keep the application code small. One naming detail is worth clearing up immediately: onsubmit.dev (form backend) is a service, while Svelte has its own on:submit event directive. They are unrelated. In this article, references to the product always mean onsubmit.dev (form backend), not Svelte's on:submit . The usual SvelteKit approach SvelteKit already has a solid answer for server-side form handling: form actions. A typical contact form can POST to a +page.server.ts action, where you validate the fields and then do something useful with them. Conceptually, that gives you: Svelte <form> ↓ SvelteKit form action ↓ validation ↓ email provider / database / notification service ↓ your inbox This is a good architecture when submitting the form kicks off application-specific business logic. For a simple portfolio, landing page, documentation site, or “contact us” form, however, you also inherit the less interesting parts of owning that pipeline: delivery integration, configuration, error handling, spam controls, and maintenance. That's where using a dedicated form backend can make sense. Using svelte-onsubmit The Svelte integration is svelte-onsubmit . Rather than reproducing package code that might drift as its API evolves, use the current installation and usage snippet from the official integration documentation: https://onsubmit.dev/integrations That documentation is the source of truth for wiring the package into your current Svelte/SvelteKit project. The resulting architecture is deliberately simpler: Svelte <form> ↓ host
开发者
You're truncating bios with `.slice()`. `Intl.Segmenter` knows where the emoji actually end.
A 30-character bio limit that cuts off mid-emoji isn't a rendering bug — it's .length counting UTF-16 code units instead of what's on screen. Intl.Segmenter counts graphemes, words, and sentences the way a reader actually sees them, and every major browser supports it now.
AI 资讯
Great summary of the benefits of Angular when using AI tooling to generate code.
Choosing Angular in the Age of Agents Brandon Roberts Brandon Roberts Brandon Roberts Follow Jul 30 Choosing Angular in the Age of Agents # angular # ai 37 reactions 4 comments 9 min read
AI 资讯
Frontend Backend Correlated Logging: Browser Fetch Request IDs and Server Logs
Short answer: give each browser fetch a request ID, carry it to the backend in a standard HTTP header, and emit that same ID in structured logs on both sides. Keep the pricing decision itself behind a flag with an explicit evaluation ID, so a rollback can be verified instead of guessed. The browser is the first audit surface Rolling out a new pricing rule in an edtech app sounds like a feature-flag task. Operationally, it is a tracing problem with money attached. A student sees a price in the browser, the frontend calls the checkout backend, and the backend evaluates a flag before writing an order. When those events cannot be joined, a rollback turns into a debate about which request produced which price. I've been paged for missed jobs and duplicate deliveries. The same failure pattern appears here: a dashboard says the system is healthy, but the individual request that matters is hard to reconstruct. A request ID doesn't prove that a price was correct. It makes the evidence joinable. The smallest useful contract is straightforward: The browser creates a non-secret request ID for each outbound fetch. The ID travels in X-Request-ID (or the equivalent header chosen by the team). The server validates or replaces malformed values, then logs the accepted value. Every log record for the request includes the ID, route, outcome, and duration. A separate flag-evaluation ID identifies the pricing decision and its rule version. Don't put a user email, token, or price in the request ID. It's a correlation key, not an authorization mechanism or a business record. How should frontend and backend logs correlate a browser fetch request ID? The browser and server need a shared boundary, not a shared logging library. For a JavaScript or Node.js application, the fetch wrapper should generate an ID before sending the request and attach it to the headers. The Node.js service should read that header at the HTTP edge, bind it to request context, and include it in every subsequent log eve
AI 资讯
Morphing Feature in WebForms Core 2.1
WebForms Core 2.1 is coming soon from Elanat . The new version introduces a collection of capabilities designed to further expand the server-driven approach of WebForms Core. One of these new capabilities is Morphing . Morphing provides a way to synchronize an existing DOM element with a new HTML structure without necessarily replacing the existing element itself . This makes it possible to update HTML structures while preserving the identity of existing DOM elements. Morphing Morphing is a DOM synchronization mechanism that compares an existing HTML element with a new HTML structure and applies the required changes to the existing DOM. Unlike a traditional replacement operation such as: element . outerHTML = html ; Morphing does not simply discard the existing element and create another one. Instead, it analyzes the existing element and the new element and performs the necessary operations: Add new attributes Update existing attributes Remove attributes that no longer exist Add new child elements Update existing child elements Remove obsolete child elements Match elements using id and cb-data-id Preserve existing DOM element identity whenever possible Preserve registered event listeners when new Nodes have to be created The goal is to make the smallest necessary changes to the DOM. Reflection vs Morphing WebForms Core 2.1 contains both Reflection and Morphing , but they serve different purposes. Reflection is primarily a merge operation . For example, if the target contains: <div id= "userCard" > <h3> User </h3> </div> and the source contains: <div class= "premium" > <button> VIP </button> </div> Reflection can merge the source into the target, adding the class and child without treating the source as a complete replacement definition. Morphing has a different philosophy. The source represents the desired structure . If the source does not contain an element or attribute that exists in the target, Morphing can remove it. Therefore: Reflection Target + Source ↓ Merg
AI 资讯
The Audit's Blind Spot: I Weighed the Build, Not the Page
I published a post called "I Audited My Own Portfolio and Found 20 Problems" . It was an inventory: I went through my own site — a React 19 + Vite SPA with Sanity as the CMS — wrote down everything that was wrong with it, fixed what mattered, and put the before and after numbers next to each item. If you haven't read it, the only part that matters here is the methodology, and one line of it in particular: I went through the build output chunk by chunk in build/assets/ . I called that the step that hurts and the one most people skip. I still think that is true. It is also the step that guaranteed I would miss the largest thing wrong with the site. The step that worked Weighing the build output worked exactly as advertised. Finding 1 of that audit was an unoptimized PNG of a developer illustration on /gabriel-abreu , my contact page, 993 KB, sent to every visitor who landed there. It went to 23 KB. A second image, the cutout of me that sits in three different greetings, went from 358 KB to 45 KB. Those two are bundled assets. A component imports one: import p from " ../assets/developer-illustration.webp " ; Vite follows that import, hashes the file, and emits it into build/assets/ . After the build it is a file on disk with a size. Listing the directory finds it. Sorting the listing by size finds it first. There is no way to ship it and not have it show up in that step. So the method was sound within its domain: both of those images are bundled assets, and the step found both. On August 23 I opened the blog index in a browser and watched what it actually requested. Sixteen post covers, 9.88 MB. None of that could have appeared in the audit. Not because I was sloppy that day — because of where those bytes come from. Two lifecycles A bundled asset exists at build time. An import makes it a build input, the bundler makes it a build output, and anything that reads the build output sees it. A CMS image is never a build input. Nothing imports it. It arrives as a string in a
AI 资讯
Static Forms in Astro: Handling Submissions Without a Server
Static Forms in Astro: Handling Submissions Without a Server with onsubmit.dev (form backend) Astro is a great fit for content-heavy sites that ship very little JavaScript, but that creates an interesting problem as soon as you add a contact form: where does the POST request go? With onsubmit.dev (form backend) , an Astro site can submit forms to an external endpoint instead of adding its own API route or server. This is particularly useful for Astro projects deployed as static files to a CDN, GitHub Pages, or another static host. You can keep the site static while still accepting contact requests, feedback, registrations, and similar submissions. Start with the zero-JavaScript pattern The simplest approach is also the most aligned with Astro's philosophy: use the browser's native form submission behavior. You don't need a hydrated component merely to collect a few fields. A regular HTML form can make a POST request directly to a form backend: --- // src/pages/contact.astro --- <form method="POST" action="https://onsubmit.dev/f/YOUR_FORM_ID"> <label> Name <input type="text" name="name" required /> </label> <label> Email <input type="email" name="email" required /> </label> <label> Message <textarea name="message" required></textarea> </label> <button type="submit">Send message</button> </form> Replace YOUR_FORM_ID with the endpoint supplied for your form. There is no client framework involved here. The browser serializes the named fields and sends them directly when the visitor clicks the button. That has several nice properties for an Astro project: No Astro server endpoint is required. No React, Vue, or other client runtime needs to be hydrated. The form still works when JavaScript is unavailable. Your static deployment remains static. It is worth remembering that native HTML already does a lot of work. required , type="email" , labels, and standard browser submission cover many simple forms without additional JavaScript. Where astro-onsubmit fits For Astro-specif
AI 资讯
The Evolution of Web Forms — Part 3
The Evolution of Web Forms — Part 3: React Hook Form, Validation Libraries, and Zod In Part 2, we learned that React solved the problem of manually updating the DOM. Instead of writing: emailError . textContent = " Email already exists " ; emailInput . setAttribute ( " aria-invalid " , " true " ); React allowed us to describe the interface from state: < input aria-invalid = { Boolean ( errors . email ) } /> { errors . email && ( < p > { errors . email } </ p > )} However, React did not automatically manage: Form values Validation errors Touched fields Dirty fields Submission state Reset behavior Dynamic fields Backend errors Performance Developers still had to build those features manually. That created the need for form-management libraries. This part covers: React Hook Form’s philosophy and architecture React Hook Form’s core APIs Validation libraries React Hook Form with Zod and TypeScript By the end, we will build a production-style registration form using: React + TypeScript + React Hook Form + Zod + An API layer Stage 9: React Hook Form Deep Dive React Hook Form is not simply a shorter way to write controlled React forms. It uses a different architectural philosophy. A traditional controlled input stores its value in React state: const [ email , setEmail ] = useState ( "" ); < input value = { email } onChange = { ( event ) => { setEmail ( event . target . value ); } } /> Every keystroke produces a state update: User types ↓ onChange runs ↓ setEmail runs ↓ Component renders again ↓ Input receives the new value React Hook Form prefers native, uncontrolled inputs when possible. < input { ... register ( " email " ) } /> The browser stores the current value inside the input element. React Hook Form registers the input, listens to its events, tracks relevant form state, and reads its value when required. React Hook Form’s official documentation describes register() as the mechanism that connects an input to validation, value tracking, and submission. Controlled vers