惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Jina AI
Jina AI
V
Visual Studio Blog
博客园 - 司徒正美
TaoSecurity Blog
TaoSecurity Blog
博客园 - 聂微东
IT之家
IT之家
博客园_首页
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - Franky
雷峰网
雷峰网
罗磊的独立博客
S
Schneier on Security
C
Cybersecurity and Infrastructure Security Agency CISA
The Cloudflare Blog
T
Tailwind CSS Blog
B
Blog RSS Feed
H
Help Net Security
T
The Blog of Author Tim Ferriss
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threatpost
C
CERT Recently Published Vulnerability Notes
博客园 - 三生石上(FineUI控件)
P
Palo Alto Networks Blog
I
Intezer
G
GRAHAM CLULEY
Engineering at Meta
Engineering at Meta
S
Securelist
J
Java Code Geeks
V
V2EX
Y
Y Combinator Blog
Simon Willison's Weblog
Simon Willison's Weblog
L
LINUX DO - 热门话题
云风的 BLOG
云风的 BLOG
Spread Privacy
Spread Privacy
MongoDB | Blog
MongoDB | Blog
P
Privacy International News Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
B
Blog
Forbes - Security
Forbes - Security
Google Online Security Blog
Google Online Security Blog
Help Net Security
Help Net Security
S
SegmentFault 最新的问题
N
Netflix TechBlog - Medium
Webroot Blog
Webroot Blog
Microsoft Security Blog
Microsoft Security Blog
SecWiki News
SecWiki News
Scott Helme
Scott Helme
aimingoo的专栏
aimingoo的专栏
N
News and Events Feed by Topic

Deno

Deno 2.8 | Deno Claw Patrol: an open-source security firewall for agents | Deno Fresh 2.3: Zero JS by default, View Transitions, and Temporal support | Deno Deno 2.7: Temporal API, Windows ARM, and npm overrides | Deno Build a dinosaur runner game with Deno, pt. 6 | Deno Build a dinosaur runner game with Deno, pt. 5 | Deno Deno Deploy is Generally Available | Deno Introducing Deno Sandbox | Deno Build a dinosaur runner game with Deno, pt. 4 | Deno Build a dinosaur runner game with Deno, pt. 3 | Deno Build a dinosaur runner game with Deno, pt. 2 | Deno React / Next.js Denial-of-Service Vulnerability: Deno Deploy users protected | Deno Deno 2.6: dx is the new npx | Deno Build a dinosaur runner game with Deno, pt. 1 | Deno React Server Functions / Next.js Vulnerability: Deno Deploy users protected | Deno My highlights from the new Deno Deploy | Deno Deno's Other Open Source Projects | Deno How Deno protects against npm exploits | Deno Help Us Raise $200k to Free JavaScript from Oracle | Deno Deno 2.5: Permissions in the config file | Deno Fresh 2.0 Graduates to Beta, Adds Vite Support | Deno Deno 2.4: deno bundle is back | Deno JavaScript™ Trademark Update | Deno What's coming to JavaScript | Deno A brief history of JavaScript | Deno Reports of Deno's Demise Have Been Greatly Exaggerated | Deno An Update on Fresh | Deno How Plaid migrated 100 services to a new database platform 5x faster with Deno | Deno Deno 2.3: Improved deno compile, local npm packages, and more | Deno Add JSR packages with pnpm and Yarn | Deno Zero-config Debugging with Deno and OpenTelemetry | Deno Exploring Art with TypeScript, Jupyter, Polars, and Observable Plot | Deno Deno v Oracle Update 3: Fighting the JavaScript Trademark | Deno Build a custom RAG AI agent in TypeScript and Jupyter | Deno How to get deep traces in your Node.js backend with OTel and Deno | Deno toranoana.deno #20 登録受付中(2025年3月14日) | Deno Node just added TypeScript support. What does that mean for Deno? | Deno The Dino 🦕, the Llama 🦙, and the Whale 🐋 | Deno Publish a lint rule, get a prize | Deno Deno 2.2: OpenTelemetry, Lint Plugins, node:sqlite | Deno If you're not using npm specifiers, you're doing it wrong | Deno How Deno's documentation is evolving | Deno Oracle justified its JavaScript trademark with Node.js—now it wants that ignored | Deno Introducing the JSR open governance board | Deno Intro to Wasm in Deno | Deno Announcing OpenAI on JSR | Deno Deno in 2024 | Deno Goodbye WinterCG, welcome WinterTC | Deno Build a SolidJS app with Deno | Deno Run your Next.js SSR app on Deno Deploy | Deno Solve Advent of Code 2024 with Deno and Win Prizes! | Deno Deno v. Oracle: Canceling the JavaScript Trademark | Deno Deno 2.1: Wasm Imports and other enhancements | Deno Build a Typesafe API with tRPC and Deno | Deno Self-contained Executable Programs with Deno Compile | Deno Build a Database App with Drizzle ORM and Deno | Deno Introducing your new JavaScript package manager: Deno | Deno Announcing Growthbook on JSR | Deno Build an Astro site with Deno | Deno How to convert CommonJS to ESM | Deno Announcing Deno 2 | Deno The Final Touches: What’s New In v2.0.0-rc.10 | Deno Announcing Stable V8 Bindings for Rust | Deno Deno 2.0 Release Candidate | Deno Secure, efficient private npm registries with Cloudsmith and Deno | Deno Painting the Plane as We Fly It: Designing JSR | Deno Introducing Web Cache API support on Deno Deploy | Deno Deno 1.46: The Last 1.x Release | Deno Protect your cloud spend with new Deno Deploy spend limits | Deno What we got wrong about HTTP imports | Deno Benchmarking AWS Lambda Cold Starts Across JavaScript Runtimes | Deno Announcing Supabase on JSR | Deno Deno 1.45: Workspace and Monorepo Support | Deno Introducing KV Backup for Deno Subhosting | Deno A Gentle Intro to TypeScript | Deno Announcing Hono on JSR | Deno How We Made the Deno Language Server Ten Times Faster | Deno How the Guardian uses Deno to audit accessibility and performance across their 2.7 million articles | Deno Introducing More Flexible Domain Association for Deno Subhosting | Deno The stabilization process of the Standard Library has begun | Deno Deno 1.44: Private npm registries, improved Node.js compat, and performance boosts | Deno How we built a secure, performant, multi-tenant cloud platform to run untrusted code | Deno The Deno Standard Library is now available on JSR | Deno How to document your JavaScript package | Deno Your Low Code Solution Needs an Escape Hatch | Deno Deno 1.43: Improved Language Server performance | Deno How Slack used Deno to save months of engineering effort in launching their new platform | Deno JSR Is Not Another Package Manager | Deno Announcing the Hookdeck SDK on JSR | Deno Announcing the Neon Serverless Driver on JSR | Deno An intro to TSConfig for JavaScript Developers | Deno How we built JSR | Deno How Netlify used Deno Subhosting to build a successful edge functions product | Deno Introducing Simpler Project Creation in Deno Deploy | Deno Deno 1.42: Better dependency management with JSR | Deno Introducing deployctl, the command line interface for Deno Deploy | Deno Introducing JSR - the JavaScript Registry | Deno How to add Monaco to a Next.js app and securely run untrusted user code | Deno Survey Results and Roadmap | Deno Deno 1.41: smaller deno compile binaries | Deno
A Whole Website in a Single JavaScript File, cont'd | Deno
Leo Kettmeir · 2022-09-13 · via Deno

Back in April, we published “A Whole Website in a Single JavaScript File”. However, based on some comments, we realized we didn’t fully communicate what we felt was unique about such an exercise — its simplicity and performance without sacrificing functionality users expect from modern websites.

So this is a follow up blog post and a new playground demonstrating a fully capable web app with dynamic API endpoints, dynamic rendering, form functionality — all within a single JavaScript file.

Searching for a bagel

Dynamic Rendering

A screenshot of the landing page with dynamically rendered data.

The landing page displays your location, local date, and time.

Let’s first look at how the location is grabbed:

const ip = (context.remoteAddr as Deno.NetAddr).hostname;
const res = await fetch("http://ip-api.com/json/" + ip);
const data: APIData = await res.json();
return ssr(() => <Landing {...data} />);

First we get the IP address, which with router is available in the second argument in the callback for a route. Once we have the IP address, we make an http request to IP-API, which returns location data, such as city and country. We pass this data to the <Landing> component, where it’s rendered.

To show the local date and time, we render the Date constructor with timezone as a parameter, in the component. Note that timezone is part of the response from the IP address, along with city and country.

function Landing({
  country,
  city,
  timezone,
}: APIData) {
  return (
    <div class="min-h-screen p-4 flex gap-12 flex-col items-center justify-center">
      <h1 class="text-2xl font-semibold">
        Welcome to Bagel Search
      </h1>
      <p class="max-w-prose">
        It's currently {new Date().toLocaleString("en-US", {
          dateStyle: "full",
          timeStyle: "medium",
          timeZone: timezone,
        })} in {city}, {country}—the perfect time and place to look up a bagel.
      </p>
      <a
        href="/search"
        class="px-4 py-2.5 rounded-md font-medium leading-none bg-gray-100 hover:bg-gray-200"
      >
        Click here to search for bagels
      </a>
    </div>
  );
}

Dynamic Routing

A bagel page

To showcase dynamic routing, we’ve dynamically generated a route for each bagel that follows this pattern: /bagels/:id.

As mentioned in the previous post, router uses URLPattern under the hood, so we can do pattern matching using the appropriate URLPattern syntax. In this case, we have /bagels/:id, which means that it will match for any path that will be /bagels/ followed by any valid value (e.g. /bagels/foo, though it will fail to match any subpaths like /bagels/foo/bar).

serve(router(
  {
    "/bagels/:id": (_req, _context, matches) => {
      return ssr(() => <Bagel id={matches.id} />);
    },
    
  },
));

We can grab the :id from the path with matches.id, since router creates a key-value with id as key and a string as value in matches.

Then, we pass the id to the <Bagel> component:

function Bagel({ id }: { id: string }) {
  const name = id.replaceAll("-", " ");
  const bagel = bagels.find((bagel) =>
    bagel.name.toLowerCase() === name.toLowerCase()
  );

  if (bagel === undefined) {
    return (
      <div>
        The bagel '{name}' does not exist
      </div>
    );
  }

  return (
    <div class="min-h-screen p-4 flex flex-col items-center justify-center">
      <div class="w-3/4 lg:w-1/4">
        <div class="w-full bg-gray-200 rounded-lg overflow-hidden">
          <img
            src={bagel.image}
            class="w-full object-center object-cover"
            alt={bagel.name}
          />
        </div>
        <div class="mt-3 flex items-center justify-between">
          <h1 class="font-semibold">{bagel.name}</h1>
          <p class="text-lg font-medium text-gray-900">
            ${bagel.price.toFixed(2)}
          </p>
        </div>
        <p class="mt-1 text-gray-600">
          {bagel.description}
        </p>
        <div class="mt-3 flex items-center justify-between">
          <div>
            <a href="/" class="underline text-blue-400">Home</a>
          </div>
          <div>
            <a href="/search" class="underline text-blue-400">Back to Search</a>
          </div>
        </div>
      </div>
    </div>
  );
}

First, we slugify the id to make it more human-readable. Next, we use that slug to match against slugified version of the bagel names in our data.

If no bagel is found, we return an error. Otherwise, we render the information of the matched bagel.

Form Functionality

“This is all great, but how can I find what bagels there are?” Great question!

Searching for egg and ham in the form

We’ve added a /search page that has a text input, where you can type in something. Upon hitting enter, the results on the page will filter based on your input.

This is achieved using a form. By default, the <form> tag uses urlencoded search parameters for values. When submitting a form (in our case, by pressing the enter key), it takes the name attribute and value of the <input> tag, and encodes it for search params.

For example, our text input has attribute name="search". If we write foo and submit it, it redirects to the current page by appending querystring ?search=foo. We also set the form method to GET, so it will make a GET request instead of a POST request.

Then, our router simply needs to parse the querystring:

serve(router(
  {
    "/search": (req) => {
      const search = new URL(req.url).searchParams.get("search");
      return ssr(() => <Search search={search ?? ""} />);
    },
  },
));

Then, we pass the search value to the <Search> component:

function Search({ search }: { search: string }) {
  const foundBagels = bagels.filter((bagel) =>
    bagel.name.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <form
      method="get"
      class="min-h-screen p-4 flex gap-8 flex-col items-center justify-center"
    >
      <input
        type="text"
        name="search"
        value={search}
        class="h-10 w-96 px-4 py-3 bg-gray-100 rounded-md leading-4 placeholder:text-gray-400"
        placeholder="Search and press enter..."
      />
      <output name="result" for="search" class="w-10/12 lg:w-1/2">
        <ul class="space-y-2">
          {foundBagels.length > 0 &&
            foundBagels.map((bagel) => (
              <li class="hover:bg-gray-100 p-1.5 rounded-md">
                <a href={`/bagels/${bagel.name.replaceAll(" ", "-")}`}>
                  <div class="font-semibold">{bagel.name}</div>
                  <div class="text-sm text-gray-500">{bagel.description}</div>
                </a>
              </li>
            ))}
          <li>
            {foundBagels.length === 0 &&
              <div>No results found. Try again.</div>}
          </li>
        </ul>
      </output>
    </form>
  );
}

We filter all the bagels that do not include the search value and display them. For a seamless user experience, we also set the <input> value to search.

What’s next?

Programming means managing complexity. While there are no shortage of ways to throw together a website, the simpler and more obvious the code, the easier, faster – and more fun – it is to program.

Everything mentioned here can be viewed in this playground.