Getting Started With Fresh

Getting Started With Fresh

A tutorial for beginners about getting started with Fresh, a new and upcoming framework which uses JavaScript

Introduction

Fresh is yet another new web framework that has been introduced to help you elevate your experience of coding on the JS framework!

Fresh is a full-stack javascript framework built on Deno. It does not communicate the JavaScript to the client by default. That indicates that all of the mass delivery and calculation occurs on the server, while the client just presents little islands of UI making the process simpler. Did I also mention? There is also no concept of a build phase in Fresh, which reduces deployment time!

What is Deno?

Deno is a Javascript runtime created by Ryan Dahl; creator of NodeJS. It’s built as a solution to the various issues which comes with the c Node. In a nutshell, it is a higher-performing and more secure alternative to Node.

What is Fresh?

Currently, client-side rendering is very expensive. The framework ships hundreds of kilobytes of client-side JavaScript to users on each request. These JS bundles frequently do little more than render static content that could just as well have been served as plain HTML.

Fresh ships 0 KB of JavaScript to clients by default. It is a framework where the bulk of rendering is done on a server, and the client is only responsible for re-rendering small islands of UI.

At its center, Fresh is a routing framework and templating engine that renders pages as they are requested on a server. The framework server Preact and JSX (or TSX) is used for delivering and templating on both the server and the client.

Let’s understand some of its features:

Fresh is a cutting-edge web structure, built for speed, reliability and effortlessness. Some stand-apart features:

  • Rendering on the edge: Delivers everything into static HTML on the server.
  • Island-based client hydration for most extreme interactivity: Works with little partitions of your application which need JavaScript to be interactive.
  • Zero runtime above: No JS is transported to the client by default.
  • No build step: Builds can simply be straightforwardly deployed to the edge with Deno Deploy.
  • No configuration is necessary: There is no need to configure anything truly in-order to start developing your application with Fresh.
  • TypeScript support out of the box: No need to configure TypeScript independently in Fresh like you'd have to do in Node.js.

Quick Start

To truly make sense of what makes Fresh unique, let's scaffold an unexplored project and peek at some code:

  • Use the following snippet for Shell (Mac, Linux):
$ curl -fsSL https://deno.land/install.sh | sh
  • Use the following snippet for PowerShell (Windows):
$ iwr https://deno.land/install.ps1 -useb | iex
  • Use the following snippet for Homebrew (Mac):
$ brew install deno

Create Project

  • Enter the following code snippet on your console to execute this:
    deno  run -A -r https://fresh.deno.dev my-app
    

run the project with:

  • Enter the following code snippet on your console to execute this:
    $ deno task start
    
  • Let's take a look at the routes/index.tsx which can be run using the code given below:
/** @jsx h */
import { h } from "preact";
import Counter from "../islands/Counter.tsx";

export default function Home() {
  return (
    <div>
      <img
        src="/logo.svg"
        height="100px"
        alt="the fresh logo: a sliced lemon dripping with juice"
      />
      <p>
        Welcome to `fresh`. Try update this message in the ./routes/index.tsx
        file, and refresh.
      </p>
      <Counter start={3} />
    </div>
  );
}

The default export of the route is the JSX template that is rendered server-side as per request. The template component itself is never rendered to the client.

This suggests the conversation starter: what if you would like to re-render a few parts of the application on the client in response to some user interaction? This is what Fresh's Islands are for. They are separate parts of an application that are re-hydrated on the client to allow interaction.

An example of an island that gives a client-side counter with increment and decrement buttons is given below. It utilizes the Preact useState hook to the counter value by running the following code:

// islands/Counter.tsx

/** @jsx h */
import { h } from "preact";
import { useState } from "preact/hooks";

interface CounterProps {
  start: number;
}

export default function Counter(props: CounterProps) {
  const [count, setCount] = useState(props.start);
  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count - 1)}>-1</button>
      <button onClick={() => setCount(count + 1)}>+1</button>
    </div>
  );

Fresh is not only a Frontend framework but a fully integrated system for writing websites. You can arbitrarily handle requests of any kind, return custom responses, make database requests, and more. This route returns a plain text HTTP response rather than an HTML page.

Data Fetching

Server-side data fetching in Fresh framework is accomplished through async handler functions. These handler functions calls ctx.render(). The data can then be retrieved by the page component through the data property on the props. Here is an example for your reference:

interface Project {
  name: string;
  age: number;
}

export const handler: Handlers<Project> = {
  async GET(_req, ctx) {
    const project = await db.projects.findOne({ id: ctx.params.id });
    if (!project) {
      return new Response("Project not found", { status: 404 });
    }
    return ctx.render(project);
  },
};

export default function ProjectPage(props: PageProps<Project>) {
  return (
    <div>
      <h1>{props.data.name}</h1>
      <p>{props.data.age} age</p>
    </div>);
}

Conclusion

Fresh 1.0 is a stable release and can be trusted for production use and even Deno's public web services uses Fresh. They have many more visions to improve the user and developer experience which will be implemented in the coming times. You can track the change-log to follow up on more upcoming updates. Here is the link for fresh@latest

Fresh projects can be deployed manually to any platform along with deno, but it is designed to be deployed to an edge runtime like Deno Deploy for the finest experience.

Do you really think this can kill Node? Please do comment down below!

I’ll be sharing more about Island Architectures in my upcoming blogs.

Thank You 🙂