summaryrefslogtreecommitdiff
path: root/src/pages
diff options
context:
space:
mode:
Diffstat (limited to 'src/pages')
-rw-r--r--src/pages/api/blob.ts20
-rw-r--r--src/pages/api/blobs.ts27
-rw-r--r--src/pages/api/revalidate.ts19
-rw-r--r--src/pages/blobs.astro8
-rw-r--r--src/pages/blobs/_components/NewShape.tsx60
-rw-r--r--src/pages/blobs/_components/ShapeEditor.tsx18
-rw-r--r--src/pages/blobs/_components/ShapePreview.tsx19
-rw-r--r--src/pages/blobs/_components/StoredShapes.tsx78
-rw-r--r--src/pages/blobs/index.astro18
-rw-r--r--src/pages/edge/index.astro2
-rw-r--r--src/pages/image-cdn.astro39
-rw-r--r--src/pages/index.astro16
-rw-r--r--src/pages/revalidation.astro61
13 files changed, 356 insertions, 29 deletions
diff --git a/src/pages/api/blob.ts b/src/pages/api/blob.ts
new file mode 100644
index 0000000..4ff37c4
--- /dev/null
+++ b/src/pages/api/blob.ts
@@ -0,0 +1,20 @@
+import type { APIRoute } from 'astro';
+import { getStore } from '@netlify/blobs';
+
+export const prerender = false;
+
+export const GET: APIRoute = async (context) => {
+ const urlParams = new URL(context.url);
+ const key = urlParams.searchParams.get('key');
+ if (!key) {
+ return new Response('Bad Request', { status: 400 });
+ }
+
+ const blobStore = getStore('shapes');
+ const blob = await blobStore.get(key, { type: 'json' });
+ return new Response(
+ JSON.stringify({
+ blob
+ })
+ );
+};
diff --git a/src/pages/api/blobs.ts b/src/pages/api/blobs.ts
new file mode 100644
index 0000000..d11aa58
--- /dev/null
+++ b/src/pages/api/blobs.ts
@@ -0,0 +1,27 @@
+import type { APIRoute } from 'astro';
+import { getStore } from '@netlify/blobs';
+
+export const prerender = false;
+
+export const POST: APIRoute = async ({ request }) => {
+ const parameters = await request.json();
+ const blobStore = getStore('shapes');
+ const key = parameters.name;
+ await blobStore.setJSON(key, parameters);
+ return new Response(
+ JSON.stringify({
+ message: `Stored shape "${key}"`
+ })
+ );
+};
+
+export const GET: APIRoute = async ({ request }) => {
+ const blobStore = getStore({ name: 'shapes', consistency: 'strong' });
+ const data = await blobStore.list();
+ const keys = data.blobs.map(({ key }) => key);
+ return new Response(
+ JSON.stringify({
+ keys
+ })
+ );
+};
diff --git a/src/pages/api/revalidate.ts b/src/pages/api/revalidate.ts
new file mode 100644
index 0000000..0d953a3
--- /dev/null
+++ b/src/pages/api/revalidate.ts
@@ -0,0 +1,19 @@
+import type { APIRoute } from 'astro';
+import { purgeCache } from '@netlify/functions';
+
+export const prerender = false;
+
+export const POST: APIRoute = async ({ request }) => {
+ const { tags } = await request.json();
+
+ if (!Array.isArray(tags)) {
+ return new Response(`Bad Request: expected tags attribute with array of strings in the body, got ${typeof tags}`, { status: 400 });
+ }
+
+ await purgeCache({ tags });
+ return new Response(
+ JSON.stringify({
+ invalidated: tags
+ })
+ );
+};
diff --git a/src/pages/blobs.astro b/src/pages/blobs.astro
deleted file mode 100644
index 2884c4a..0000000
--- a/src/pages/blobs.astro
+++ /dev/null
@@ -1,8 +0,0 @@
----
-import Layout from "../layouts/Layout.astro";
----
-
-<Layout title="Blobs">
- <h1 class="mb-8">Blobs x Blobs</h1>
- <p class="text-lg">Get started with Astro.js and Netlify in seconds.</p>
-</Layout>
diff --git a/src/pages/blobs/_components/NewShape.tsx b/src/pages/blobs/_components/NewShape.tsx
new file mode 100644
index 0000000..05f9e6f
--- /dev/null
+++ b/src/pages/blobs/_components/NewShape.tsx
@@ -0,0 +1,60 @@
+import { useState, useEffect } from 'react';
+import type { Dispatch, SetStateAction } from 'react';
+import ShapePreview from './ShapePreview.tsx';
+import { generateBlob } from '../../../utils';
+import type { BlobProps } from '../../../types.ts';
+
+interface Props {
+ setLastMutationTime?: Dispatch<SetStateAction<number>>;
+}
+
+export default function NewShape(props: Props) {
+ const { setLastMutationTime } = props;
+ const [blobData, setBlobData] = useState<BlobProps>();
+ const [wasUploaded, setWasUploaded] = useState<boolean>(false);
+
+ const randomizeBlob = () => {
+ setBlobData(generateBlob());
+ setWasUploaded(false);
+ };
+
+ const uploadBlob = async () => {
+ const response = await fetch('/api/blobs', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(blobData.parameters)
+ });
+ const data = await response.json();
+ if (data.message) {
+ console.log(data.message);
+ }
+ setWasUploaded(true);
+ setLastMutationTime(Date.now());
+ };
+
+ useEffect(() => {
+ if (!blobData) {
+ randomizeBlob();
+ }
+ }, [blobData]);
+
+ return (
+ <>
+ <h2 className="mb-4 text-xl text-center sm:text-xl">New Random Shape</h2>
+ <div className="w-full bg-white rounded-lg mb-6">
+ <div className="min-h-14 p-4 border-b border-neutral-200 text-neutral-900 text-center">
+ {blobData && <span>{blobData.parameters?.name}</span>}
+ </div>
+ <div className="p-4 aspect-square text-primary">{blobData && <ShapePreview {...blobData} />}</div>
+ </div>
+ <div className="flex flex-wrap justify-center gap-4">
+ <button className="btn btn-primary" onClick={randomizeBlob}>
+ Randomize
+ </button>
+ <button className="btn btn-primary" onClick={uploadBlob} disabled={wasUploaded || !blobData}>
+ Upload
+ </button>
+ </div>
+ </>
+ );
+}
diff --git a/src/pages/blobs/_components/ShapeEditor.tsx b/src/pages/blobs/_components/ShapeEditor.tsx
new file mode 100644
index 0000000..9a339cc
--- /dev/null
+++ b/src/pages/blobs/_components/ShapeEditor.tsx
@@ -0,0 +1,18 @@
+import { useState } from 'react';
+import NewShape from './NewShape.tsx';
+import StoredShapes from './StoredShapes.tsx';
+
+export default function ShapeEditor() {
+ const [lastMutationTime, setLastMutationTime] = useState<number>(null);
+
+ return (
+ <div className="flex flex-col gap-8 md:flex-row">
+ <div className="flex-1">
+ <NewShape setLastMutationTime={setLastMutationTime} />
+ </div>
+ <div className="flex-1">
+ <StoredShapes lastMutationTime={lastMutationTime} />
+ </div>
+ </div>
+ );
+}
diff --git a/src/pages/blobs/_components/ShapePreview.tsx b/src/pages/blobs/_components/ShapePreview.tsx
new file mode 100644
index 0000000..a00d2bc
--- /dev/null
+++ b/src/pages/blobs/_components/ShapePreview.tsx
@@ -0,0 +1,19 @@
+import { randomInt } from '../../../utils.ts';
+import type { BlobProps } from '../../../types.ts';
+
+export default function ShapePreview(props: BlobProps) {
+ const { svgPath, parameters } = props;
+ const gradientId = `gradient-${randomInt(10_000_000, 100_000_000)}`;
+
+ return (
+ <svg viewBox={`0 0 ${parameters.size} ${parameters.size}`} xmlns="http://www.w3.org/2000/svg" width="100%">
+ <defs>
+ <linearGradient id={gradientId} x1="0%" y1="0%" x2="0%" y2="100%">
+ <stop offset="0%" style={{ stopColor: parameters.colors[0] }} />
+ <stop offset="100%" style={{ stopColor: parameters.colors[1] }} />
+ </linearGradient>
+ </defs>
+ <path d={svgPath} fill={`url(#${gradientId})`}></path>
+ </svg>
+ );
+}
diff --git a/src/pages/blobs/_components/StoredShapes.tsx b/src/pages/blobs/_components/StoredShapes.tsx
new file mode 100644
index 0000000..e870ef5
--- /dev/null
+++ b/src/pages/blobs/_components/StoredShapes.tsx
@@ -0,0 +1,78 @@
+import { useState, useEffect } from 'react';
+import ShapePreview from './ShapePreview.tsx';
+import { generateBlob } from '../../../utils';
+import type { BlobProps } from '../../../types.ts';
+
+interface Props {
+ lastMutationTime: number;
+}
+
+export default function StoredShapes(props: Props) {
+ const { lastMutationTime } = props;
+ const [keys, setKeys] = useState<string[]>([]);
+ const [selectedKey, setSelectedKey] = useState<string>(null);
+ const [previewData, setPreviewData] = useState<BlobProps>(null);
+
+ const getBlobKeyList = async () => {
+ console.log('Fetching keys...');
+ const response = await fetch('/api/blobs', {
+ method: 'GET',
+ headers: { 'Content-Type': 'application/json' }
+ });
+ const data = await response.json();
+ if (data.keys) {
+ setKeys(data.keys);
+ }
+ };
+
+ const getBlobByKey = async (key: string) => {
+ setSelectedKey(key);
+ const params = new URLSearchParams({ key });
+ const response = await fetch(`/api/blob/?${params}`, {
+ method: 'GET'
+ });
+ const data = await response.json();
+ if (data.blob) {
+ setPreviewData(generateBlob(data.blob));
+ }
+ };
+
+ useEffect(() => {
+ getBlobKeyList();
+ }, [lastMutationTime]);
+
+ return (
+ <>
+ <h2 className="mb-4 text-xl text-center sm:text-xl">Objects in Blob Store</h2>
+ <div className="w-full bg-white rounded-lg">
+ <div className="min-h-14 p-4 text-center">
+ {keys?.length ? (
+ <div className="space-y-1">
+ {keys.map((keyName) => (
+ <button
+ key={keyName}
+ className={
+ 'btn btn-ghost btn-sm btn-block text-neutral-900 font-normal' +
+ (selectedKey === keyName ? ' bg-base-content/20 pointer-events-none' : '')
+ }
+ onClick={() => {
+ getBlobByKey(keyName);
+ }}
+ >
+ {keyName}
+ </button>
+ ))}
+ </div>
+ ) : (
+ <span className="text-neutral-900">Please upload some shapes!</span>
+ )}
+ </div>
+ {previewData && (
+ <div className="p-4 aspect-square text-primary border-t border-neutral-200">
+ <ShapePreview {...previewData} />
+ </div>
+ )}
+ </div>
+ </>
+ );
+}
diff --git a/src/pages/blobs/index.astro b/src/pages/blobs/index.astro
new file mode 100644
index 0000000..5630d6b
--- /dev/null
+++ b/src/pages/blobs/index.astro
@@ -0,0 +1,18 @@
+---
+import Layout from '../../layouts/Layout.astro';
+import Markdown from '../../components/Markdown.astro';
+import ShapeEditor from './_components/ShapeEditor.tsx';
+
+const explainer = `
+[Netlify Blobs](https://docs.netlify.com/blobs/overview/) provides an object store for any kind of data, be it JSON, binary,
+or [really](https://mk.gg/projects/chalkstream) anything else ([really!](https://mk.gg/projects/turbofan)). In this example, the blob store is used to **hold the data of user-generated random blobby shapes**.
+
+Below is an Astro island with a React component for editing, uploading and viewing blobs to the blob store 🙂.
+`;
+---
+
+<Layout title="Blobs">
+ <h1 class="mb-8">Blobs x Blobs</h1>
+ <Markdown content={explainer} class="mb-12" />
+ <ShapeEditor client:load />
+</Layout>
diff --git a/src/pages/edge/index.astro b/src/pages/edge/index.astro
index f49f3a9..8bf4a85 100644
--- a/src/pages/edge/index.astro
+++ b/src/pages/edge/index.astro
@@ -9,7 +9,7 @@ This page is using a [Netlify Edge Function](https://docs.netlify.com/edge-funct
For it to be invoked, please either run this site locally with \`netlify dev\` or deploy it to Netlify.
-Edge Functions are framework-agnostic, but are also used behind the scenes to run Next.js Middleware on Netlify.
+Edge Functions are framework-agnostic, but are also used behind the scenes to run Astro Middleware on Netlify.
There are advatanges to using Edge Functions directly, such as the ability to access & transform the response body.
[See more examples](https://edge-functions-examples.netlify.app)
diff --git a/src/pages/image-cdn.astro b/src/pages/image-cdn.astro
index 8847536..dbb8822 100644
--- a/src/pages/image-cdn.astro
+++ b/src/pages/image-cdn.astro
@@ -10,18 +10,25 @@ const sampleImage = '/images/corgi.jpg';
const ctx = getNetlifyContext();
const forceWebP = ctx === 'dev';
-const sampleImageNetlify = `/.netlify/images?url=${sampleImage}${forceWebP ? '&fm=webp' : ''}`;
+const sampleImageSrcSet = [640, 1280, 2048]
+ .map((size) => {
+ return `/.netlify/images?url=${sampleImage}&w=${size}${forceWebP ? '&fm=webp' : ''} ${size}w`;
+ })
+ .join(', ');
+const sizes = '(max-width: 1024px) 100vw, 1024px';
const astroImageSnippet = `
-## Using built-in Astro &lt;Image /&gt; component
+## Using the built-in Astro &lt;Image /&gt; component
-When running on Netlify, \`next/image\` is automatically set-up to use Netlify Image CDN for optimized images.
+Astro's \`Image\` component will automatically use Netlify Image CDN to serve optimized images.
~~~jsx
-import Image from 'next/image';
-
-// In your component
-<Image src="/images/corgi.jpg" alt="Corgi" /* ... additional props */ />
+---
+import { Image } from 'astro:assets';
+import corgi from '../assets/corgi.jpg';
+---
+// Later in your markup...
+<Image src={corgi} alt="Corgi" /* ... additional props */ />
~~~
`;
@@ -29,7 +36,7 @@ const originalVsCdnSnippet = `
## Original vs. optimized image: can you tell the difference?
In the code below, a regular \`<img>\` tag is used in both cases for a framework-agnostic example.
-Other than using \`next/image\` or rolling your own \`<img>\` tags, you can also use the excellent [unpic-img](https://unpic.pics/).
+Note that aside from Astro's \`Image\` or rolling your own \`<img>\` tags, you can also use the excellent [unpic-img](https://unpic.pics/) package.
~~~jsx
// <== On the left, the original image
@@ -37,8 +44,8 @@ Other than using \`next/image\` or rolling your own \`<img>\` tags, you can also
// ==> On the right, explicitly using Netlify Image CDN endpoint for a responsive image
<img
- srcSet="/.netlify/images?url=images/corgi.jpg&w=640 640w, /.netlify/images?url=images/corgi.jpg&w=1280 1280w, /.netlify/images?url=images/corgi.jpg&w=2048 2048w"
- sizes="(max-width: 1024px) 100vw, 1024px"
+ srcSet="${sampleImageSrcSet}"
+ sizes="${sizes}"
alt="Corgi"
/>
~~~
@@ -53,11 +60,11 @@ detection, so format is set to WebP.
<Layout title="Image CDN">
<div class="flex flex-col gap-12 sm:gap-16">
<section class="space-y-8">
- <ContextAlert addedChecksFunction={
- (ctx) => {
- return ctx === "dev" ? devModeWarning : null;
- }
- } />
+ <ContextAlert
+ addedChecksFunction={(ctx) => {
+ return ctx === 'dev' ? devModeWarning : null;
+ }}
+ />
<h1>Image CDN</h1>
</section>
<section>
@@ -77,7 +84,7 @@ detection, so format is set to WebP.
<div>
<div class="relative">
<span class="hidden absolute py-1.5 px-2.5 text-sm rounded-lg bg-neutral-900/70 top-2.5 right-2.5"></span>
- <img src={sampleImageNetlify} alt="Corgi" />
+ <img srcset={sampleImageSrcSet} alt="Corgi" />
</div>
</div>
</div>
diff --git a/src/pages/index.astro b/src/pages/index.astro
index 8955471..6e73e14 100644
--- a/src/pages/index.astro
+++ b/src/pages/index.astro
@@ -1,13 +1,21 @@
---
import Layout from '../layouts/Layout.astro';
-import Card from '../components/Card.astro';
+import ContextAlert from '../components/ContextAlert.astro';
+import Markdown from '../components/Markdown.astro';
+
+const explainer = `
+An Astro website can go way beyond static pages - on the right platform.
+
+Netlify supports not only [Streaming SSR](https://docs.astro.build/en/guides/server-side-rendering/) and fast [Edge Middleware](https://docs.astro.build/en/guides/middleware/), but also [on-demand revalidation](https://www.netlify.com/blog/cache-tags-and-purge-api-on-netlify/) and [stale-while-revalidate](https://www.netlify.com/blog/swr-and-fine-grained-cache-control/).
+Any page or data can be rebuilt only when needed, without site visitors ever getting a performance hit.
+`;
---
<Layout title="Welcome to Astro.">
- <h1 class="mb-8">Netlify Platform Starter - Astro.js</h1>
- <p class="mb-6 text-lg">Get started with Astro.js and Netlify in seconds.</p>
+ <ContextAlert class="mb-4" />
+ <h1 class="mb-10">Netlify Platform Starter for Astro</h1>
+ <Markdown content={explainer} class="text-lg mb-10" />
<p class="mb-8">
<a href="https://docs.netlify.com/frameworks/astro/" class="btn btn-lg btn-primary sm:btn-wide">Read the Docs</a>
</p>
- <Card title="Random Title" text="Long random text about Astro.js. Get started with Astro.js and Netlify in seconds." />
</Layout>
diff --git a/src/pages/revalidation.astro b/src/pages/revalidation.astro
new file mode 100644
index 0000000..f7d4f6e
--- /dev/null
+++ b/src/pages/revalidation.astro
@@ -0,0 +1,61 @@
+---
+import Layout from '../layouts/Layout.astro';
+import ContextAlert from '../components/ContextAlert.astro';
+import Markdown from '../components/Markdown.astro';
+import { cacheHeaders, randomInt } from '../utils';
+
+export const prerender = false;
+
+const tags = ['/revalidation', 'cats-related', 'all-pets-related'];
+const headers = cacheHeaders(365, tags);
+
+Object.entries(headers).map(([k, v]) => {
+ Astro.response.headers.set(k, v);
+});
+
+const explainer = `
+This is a server-rendered page, last created at \`${new Date().toUTCString()}\` with a few extra response headers:
+
+~~~js
+${JSON.stringify(headers, null, 2)}
+~~~
+
+Meaning: **for browsers,** this is a non-cacheable page. At the **CDN level,** it *is* cacheable for up to a year (and Netlify also automatically busts the cache on new deployments, by default).
+
+But there's something more: the \`Cache-Tag\` header, in tandem with the [purge API](https://docs.netlify.com/platform/caching/#on-demand-invalidation), allows a developer to invalidate at will any
+pieces of content (pages, JSON responses, or whatnot) based on the tags associated with them. Tags are completely up to you to decide on, and allow for very powerful patterns.
+
+In real-world applications, you may want to use [stale-while-revalidate](https://docs.netlify.com/platform/caching/#stale-while-revalidate-directive) as well, so that end-users don't experience
+a performance hit as pages are being rebuilt.
+
+Use the button below to invlidate a random tag out of this page's tags, then refresh the page.
+`;
+
+const exampleTag = tags[randomInt(0, tags.length - 1)];
+---
+
+<Layout title="Revalidation">
+ <h1 class="mb-10">Revalidating Server Content</h1>
+ <Markdown content={explainer} class="mb-10" />
+ <button class="revalidate-button btn btn-primary" data-tag={exampleTag}>Invalidate tag: {exampleTag}</button>
+ <button class="btn btn-primary" onclick="location.reload()">Reload page</button>
+</Layout>
+
+<script>
+ function revalidate(tag: string) {
+ fetch('/api/revalidate', {
+ method: 'POST',
+ body: JSON.stringify({ tags: [tag] }),
+ headers: {
+ 'Content-Type': 'application/json'
+ }
+ });
+ alert(`Invalidated tag: ${tag}`);
+ }
+
+ const revalidateButton = document.querySelectorAll('button.revalidate-button')[0];
+ revalidateButton.addEventListener('click', (e) => {
+ const tag = (e.target as HTMLButtonElement).getAttribute('data-tag');
+ revalidate(tag);
+ });
+</script>