Alright, let's go over some of the features of Fresh. We've got static files we'll talk about, routes and routing, data fetching, middleware, error pages, styling, and then we'll get to Islands.
So first up we have static files. All static assets can be found in the Static folder. Static assets, aside from image and source tags, do not have cache headers set on them. You can set cache headers manually or you can use the built-in asset helper to automatically cache an asset for a year. Here's an example of the asset helper in action. So I have this on my style sheet. I'm using the asset helper and what happens is it generates a unique URL which is composed of the asset file path, followed by a query string with one key, underscore FRSH, underscore C with a value that is the build ID from the deployment. And you can see, as I mentioned, there also gets this in the cache control headers set in the response. So we have it there for a year.
Alright, let's dig into routes and routing. There are three kinds of routes. There's the handler route, which is typically for APIs, the component route, which is for pages, and then the hybrid route. And for hybrid routes, it's for pages that require handlers routes, for example, a login page or a search page. Like in other frameworks, routes can also be dynamic. You can see in the table here that I took from the fresh documentation, that there are many types of file-based routing patterns that are supported. One thing to note, though, is fresh only supports server-side rendering. So there is no concept of something like get static paths in Next.js or Astro since pages are never statically generated.
Alright, let's look at the data-fetching story. So for data-fetching, we have handler routes, which I just mentioned, and we can also use hybrid routes to handle data-fetching. For a handler route, all that is required is exporting a function that takes two arguments, a request and a context, and it returns a response. So in this case here, we have a handler which is using the, this is the jokes API that ships with the fresh demo site, and we can see here it's just generating a list of random jokes from an array, and then it's returning that as a response. For hybrid routes, we define functions for actions in an exported variable called handler. We name the async functions in the handler object after HTTP verbs. For example, get. As the handler route in the previous example returns a response, typically in a hybrid route, you'll want to return the result of the context render method. Think of context render as passing in server-side rendered props to the page being rendered. When I say props, I mean pre-act props or react props if you're new to pre-act. Looking at the example on the slide, one thing to note about props and fresh is that it's not props.movies, the props from context.render are always in the props.data property.
Comments