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

推荐订阅源

大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
量子位
A
Arctic Wolf
L
Lohrmann on Cybersecurity
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
WordPress大学
WordPress大学
V
Vulnerabilities – Threatpost
博客园 - Franky
C
Cyber Attacks, Cyber Crime and Cyber Security
The Cloudflare Blog
Last Week in AI
Last Week in AI
The Hacker News
The Hacker News
I
Intezer
J
Java Code Geeks
P
Privacy International News Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
Secure Thoughts
Cisco Talos Blog
Cisco Talos Blog
阮一峰的网络日志
阮一峰的网络日志
S
Securelist
Security Latest
Security Latest
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
小众软件
小众软件
Jina AI
Jina AI
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
博客园_首页
酷 壳 – CoolShell
酷 壳 – CoolShell
T
The Exploit Database - CXSecurity.com
雷峰网
雷峰网
T
Tenable Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Privacy & Cybersecurity Law Blog
Simon Willison's Weblog
Simon Willison's Weblog
博客园 - 【当耐特】
T
Threat Research - Cisco Blogs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
MongoDB | Blog
MongoDB | Blog
D
DataBreaches.Net
N
News | PayPal Newsroom
Google Online Security Blog
Google Online Security Blog
K
Kaspersky official blog
H
Help Net Security
宝玉的分享
宝玉的分享
罗磊的独立博客
Webroot Blog
Webroot Blog
月光博客
月光博客
B
Blog RSS Feed
Recorded Future
Recorded Future

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
How to Build a Blog with Fresh | Deno
Andy Jiang · 2022-10-25 · via Deno

Fresh is an edge-first web framework that delivers zero JavaScript to the client by default with no build step. It’s optimized for speed and, when hosted on the edge with Deno Deploy, can be fairly trivial to get a perfect Lighthouse pagespeed score.

This post will show you how to build your own markdown blog with Fresh and deploy it to the edge with Deno Deploy.

View source here.

Create a new Fresh app

Fresh comes with its own install script. Simply run:

deno run -A -r https://fresh.deno.dev my-fresh-blog

We’ll select yes for Tailwind and VSCode.

Let’s run deno task start to see the default app:

Our default fresh app

Voila!

Update the directory structure

The Fresh init script scaffolds a generic app directory. So let’s modify it to fit the purposes of a blog.

Let’s add a posts folder that will contain all markdown files:

And remove the unnecessary components, islands, and routes/api folders:

$ rm -rf components/ islands/ routes/api

The final top-level directory structure should look something like this:

my-fresh-blog/
├── .vscode
├── posts
├── routes
├── static
├── deno.json
├── dev.ts
├── fresh.gen.ts
├── import_map.json
├── main.ts
├── README.md
└── twins.config.ts

Write a dummy blog post

Let’s create a simple markdown file called first-blog-post.md in ./posts and include the following frontmatter:

---
title: This is my first blog post!
published_at: 2022-11-04T15:00:00.000Z
snippet: This is an excerpt of my first blog post.
---

Hello, world!

Next, let’s update the routes to render the blog posts.

Update the routes

Let’s start with index.tsx, which will render the blog index page. Feel free to delete everything in this file so we can start from scratch.

Getting post data

We’ll create an interface for a Post object, which includes all of the properties and their types. We’ll keep it simple for now:

interface Post {
  slug: string;
  title: string;
  publishedAt: Date;
  content: string;
  snippet: string;
}

Next, let’s create a custom handler function that will grab the data from the posts folder and transform them into data that we can easily render with tsx.

import { Handlers } from "$fresh/server.ts";

export const handler: Handlers<Post[]> = {
  async GET(_req, ctx) {
    const posts = await getPosts();
    return ctx.render(posts);
  },
};

Let’s define a helper function called getPosts, which will read the files from ./posts directory and return them as a Post array. For now, we can stick it in the same file.

async function getPosts(): Promise<Post[]> {
  const files = Deno.readDir("./posts");
  const promises = [];
  for await (const file of files) {
    const slug = file.name.replace(".md", "");
    promises.push(getPost(slug));
  }
  const posts = await Promise.all(promises) as Post[];
  posts.sort((a, b) => b.publishedAt.getTime() - a.publishedAt.getTime());
  return posts;
}

We’ll also define a helper function called getPost, a function that accepts slug and returns a single Post. Again, let’s stick it in the same file for now.


import { extract } from "$std/encoding/front_matter.ts";
import { join } from "$std/path/mod.ts";

async function getPost(slug: string): Promise<Post | null> {
  const text = await Deno.readTextFile(join("./posts", `${slug}.md`));
  const { attrs, body } = extract(text);
  return {
    slug,
    title: attrs.title,
    publishedAt: new Date(attrs.published_at),
    content: body,
    snippet: attrs.snippet,
  };
}

Now let’s put these functions to use and render the blog index page!

Rendering the blog index page

Each route file must export a default function that returns a component.

We’ll name our main export function BlogIndexPage and render the post data through that:

import { PageProps } from "$fresh/server.ts";

export default function BlogIndexPage(props: PageProps<Post[]>) {
  const posts = props.data;
  return (
    <main class="max-w-screen-md px-4 pt-16 mx-auto">
      <h1 class="text-5xl font-bold">Blog</h1>
      <div class="mt-8">
        {posts.map((post) => <PostCard post={post} />)}
      </div>
    </main>
  );
}

We’ll also need to define <PostCard>:

function PostCard(props: { post: Post }) {
  const { post } = props;
  return (
    <div class="py-8 border(t gray-200)">
      <a class="sm:col-span-2" href={`/${post.slug}`}>
        <h3 class="text(3xl gray-900) font-bold">
          {post.title}
        </h3>
        <time class="text-gray-500">
          {new Date(post.publishedAt).toLocaleDateString("en-us", {
            year: "numeric",
            month: "long",
            day: "numeric",
          })}
        </time>
        <div class="mt-4 text-gray-900">
          {post.snippet}
        </div>
      </a>
    </div>
  );
}

Let’s run our server with deno task start and check localhost:

A first look at our blog index page

Awesome start!

But clicking on the post doesn’t work yet. Let’s fix that.

Creating the post page

In /routes/, let’s rename [name].tsx to [slug].tsx.

Then, in [slug].tsx, we’ll do something similar to index.tsx: create a custom handler to get a single post and export a default component that renders the page.

Since we’ll be reusing the helper functions getPosts and getPost, as well as the interface Post, let’s refactor them into a separate utility file called posts.ts under a new folder called utils:

my-fresh-blog/
…
├── utils
│   └── posts.ts
…

Note: you can add "/": "./", "@/": "./" to your import_map.json so that you can import from posts.ts with a path relative to root:

import { getPost } from "@/utils/posts.ts";

In our /routes/[slug].tsx file, let’s create a custom handler to get the post and render it through the component. Note that we can access ctx.params.slug since we used square brackets in the filename [slug].tsx.

import { Handlers } from "$fresh/server.ts";
import { getPost, Post } from "@/utils/posts.ts";

export const handler: Handlers<Post> = {
  async GET(_req, ctx) {
    const post = await getPost(ctx.params.slug);
    if (post === null) return ctx.renderNotFound();
    return ctx.render(post);
  },
};

Then, let’s create the main component for rendering post:

import { PageProps }

export default function PostPage(props: PageProps<Post>) {
  const post = props.data;
  return (
    <main class="max-w-screen-md px-4 pt-16 mx-auto">
      <h1 class="text-5xl font-bold">{post.title}</h1>
      <time class="text-gray-500">
        {new Date(post.publishedAt).toLocaleDateString("en-us", {
          year: "numeric",
          month: "long",
          day: "numeric"
        })}
      </time>
      <div class="mt-8"
        dangerouslySetInnerHTML={{ __html: post.content }}
        />
    </main>
  )
}

Let’s check our localhost:8000 and click on the post:

Our first blog post

There it is!

Parsing markdown

Currently, this does not parse markdown. If you write something like this:

raw markdown blog post file

It’ll show up like this:

unprocessed markdown on the blog

In order to parse markdown, we’ll need to import the module gfm and pass post.content through the function gfm.render().

Let’s add this line to import_map.json:

"$gfm": "https://deno.land/x/gfm@0.1.26/mod.ts"

Then, in /routes/[slug].tsx, we’ll need to import both CSS and render functions from $gfm, as well as <Head> from Fresh:

import { CSS, render } from "$gfm";
import { Head } from "$fresh/runtime.ts";

And update our PostPage component to:

export default function PostPage(props: PageProps<Post>) {
  const post = props.data;
  return (
    <>
      <Head>
        <style dangerouslySetInnerHTML={{ __html: CSS }} />
      </Head>
      // ...
      <div
        class="mt-8 markdown-body"
        dangerouslySetInnerHTML={{ __html: render(post.content) }}
      />
    </>
  );
}

Note we’ll need to include the class markdown-body on the div for the gfm stylesheet to work.

Now markdown looks much better:

markdown working even better

Deploying to the edge

Deno Deploy is our globally distributed v8 isolate cloud where you can host arbitrary JavaScript. It’s great for hosting serverless functions as well as entire websites and applications.

We can easily deploy our new blog to Deno Deploy with the following steps.

  • Create a GitHub repo for your new blog
  • Go to https://dash.deno.com/ and connect your GitHub
  • Select your GitHub organization or user, repository and branch
  • Select “Automatic” deployment mode and main.ts as an entry point
  • Click “Link”, which will start the deployment

When the deployment is complete, you’ll receive a URL that you can visit. Here’s a live version.

What’s next?

This is a simple tutorial on building a blog with Fresh that demonstrates how Fresh retrieves data from a filesystem, which it renders into HTML, all on the server.

For a more in depth walkthrough, check out this video with Luca, who builds a blog and deploys it to Deno Deploy.

Stuck? Get help with Fresh and Deno on our Discord or Twitter!