The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
add data fetching and caching blog
Jon Meyers95163650deb9
diff --git a/apps/www/_blog/2022-11-18-fetching-and-caching-supabase-data-in-next-js-server-components.mdx b/apps/www/_blog/2022-11-18-fetching-and-caching-supabase-data-in-next-js-server-components.mdxindex c660a5b183f..6024141781f 100644--- a/apps/www/_blog/2022-11-18-fetching-and-caching-supabase-data-in-next-js-server-components.mdx+++ b/apps/www/_blog/2022-11-18-fetching-and-caching-supabase-data-in-next-js-server-components.mdx@@ -1,7 +1,7 @@---title: 'Fetching and caching Supabase data in Next.js 13 Server Components'description: 'Next.js 13 introduces new data fetching and caching methods to enable React Server Components and Suspense.'-author: jonmeyers+author: jonmeyers_ioimage: TODOthumb: TODOtags:@@ -16,13 +16,13 @@ date: '2022-11-18'toc_depth: 3----The biggest announcement from Next.js Conf 2022 was the release of Next.js 13)[https://nextjs.org/blog/next-13](https://nextjs.org/blog/next-13), which introduces a collection of improvements, most exciting of which is Server Components. The combination of Server Components and Suspense allow for a more streamlined, reimagined way to fetch and cache data. This provides excellent DX improvements — such as async components — and aligns the Next framework even closer with the future of React.+The biggest announcement from Next.js Conf 2022 was the [release of Next.js 13](https://nextjs.org/blog/next-13), which introduces a collection of improvements, most exciting of which is Server Components. The combination of Server Components and Suspense allow for a more streamlined, reimagined way to fetch and cache data in Next.js applications. This provides excellent DX improvements — such as async components — and aligns the Next framework even closer with the future of React.-This article is going to look at how we can use these brand new async components to simplify fetching and caching data from Supabase. We will look at authentication and using the Next.js Auth Helpers to make authenticated Supabase queries from Server Components in a separate article. Coming soon!+This article is going to look at how we can use these brand new async components to simplify fetching and caching data from Supabase. We will look all things auth in a separate article. Check out the [Server Components example in the Auth Helpers repo](https://github.com/supabase/auth-helpers/tree/main/examples/nextjs-server-components) if you just can't wait!-> To learn more about any of the concepts covered in this article, check out [Next.js' beta docs](https://beta.nextjs.org/docs).+> To learn more about any of the concepts covered in this article, check out the [Next.js beta docs](https://beta.nextjs.org/docs).-A good distinction to understand is that Next.js 13 is stable and ready for production, however, the `app` directory is still in beta and likely to change. This article will be focusing on the app directory, Server Components and Suspense so let's get experimental!+A good distinction to understand at this point, is that Next.js 13 is stable and ready for production, however, the `app` directory is still in beta and likely to change. This article will be focusing on the app directory, Server Components and Suspense so let's get experimental!> For an example of the code covered in this tutorial, check out [this repo](https://github.com/dijonmusters/fetching-and-caching-supabase-data-in-next-js-13-server-components).@@ -53,9 +53,9 @@ And navigate to [http://localhost:3000](http://localhost:3000).This should look pretty familiar, and scanning the folder structure for the app, it should look almost identical to Next.js 12, but with a new folder called `app`. This is where the new data fetching and caching magic takes place. 🪄-Each folder within the `app` directory represents a route in our application. Each folder must have a `page` component, which is rendered when the user navigates to the route, and an optional `layout`, `loading` and `error` component.+Each folder within the `app` directory represents a route in our application. Each folder must have a `page` component, which is rendered when the user navigates to the route, and optional `layout`, `loading` and `error` components.-> Learn more about page, layout, loading and error components in the Next.js docs [TODO link to each of those docs].+> Learn more about [Page](https://beta.nextjs.org/docs/api-reference/file-conventions/page), [Layout](https://beta.nextjs.org/docs/api-reference/file-conventions/layout), [Loading](https://beta.nextjs.org/docs/api-reference/file-conventions/loading) and [Error](https://beta.nextjs.org/docs/api-reference/file-conventions/error) components in the [Next.js beta docs](https://beta.nextjs.org/docs).Before we jump into fetching data, we need some data to fetch. Let’s [create a new Supabase project](https://app.supabase.com).@@ -78,15 +78,15 @@ valuesThis will create a table called `posts`, and populate it with some example data.-Let’s install the [`supabase-js` library](https://www.npmjs.com/package/@supabase/supabase-js) to fetch our `posts`.+Let’s install the [supabase-js library](https://www.npmjs.com/package/@supabase/supabase-js) to fetch our `posts`.```bashnpm install @supabase/supabase-js```-And add a `.env.local` file with the following environment variables.+And add a `.env.local` file with the following environment variables:-``` title=".env.local"+```title=".env.local"NEXT_PUBLIC_SUPABASE_URL=your-supabase-urlNEXT_PUBLIC_SUPABASE_ANON_KEY=your-supabase-anon-key```@@ -96,28 +96,28 @@ NEXT_PUBLIC_SUPABASE_ANON_KEY=your-supabase-anon-keyLastly, we need to create a Supabase client. Create a file at `utils/supabase.ts` with the following content:```tsx title="utils/supabase.ts"-import { createClient } from "@supabase/supabase-js";+import { createClient } from '@supabase/supabase-js'export default createClient(process.env.NEXT_PUBLIC_SUPABASE_URL!,process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!-);+)```Okay, let’s look at some different data fetching and caching strategies.# Static-By default any page component in the `app` folder is a Server Component, and its data is fetched and cached by Next.js every time we build a new version of our application. This is the equivalent of exporting a `getStaticProps` function from a component in the `pages` directory.+By default any page component in the `app` folder is a Server Component, and its data is fetched and cached by Next.js every time we build a new version of our application. This is equivalent to exporting a `getStaticProps` function from a component in the `pages` directory.Let’s create a new file at `app/static/page.tsx` and populate with the following:```jsx title="app/static/page.tsx"-import supabase from "../../utils/supabase";+import supabase from '../../utils/supabase'export default async function Posts() {- const { data: posts } = await supabase.from("posts").select();- return <pre>{JSON.stringify(posts, null, 2)}</pre>;+ const { data: posts } = await supabase.from('posts').select()+ return <pre>{JSON.stringify(posts, null, 2)}</pre>}```@@ -128,21 +128,21 @@ Server Components support async/await by default, and suspend the rendering of tLet’s modify this component to render out a collection of `<Link />` components, that navigate to a dedicated page for each post.```tsx title="app/static/page.tsx"-import Link from "next/link";-import supabase from "../../utils/supabase";+import Link from 'next/link'+import supabase from '../../utils/supabase'export default async function Posts() {- const { data: posts } = await supabase.from("posts").select("id, title");+ const { data: posts } = await supabase.from('posts').select('id, title')if (!posts) {- return <p>No posts found.</p>;+ return <p>No posts found.</p>}return posts.map((post) => (<p key={post.id}><Link href={`/static/${post.id}`}>{post.title}</Link></p>- ));+ ))}```@@ -151,35 +151,31 @@ export default async function Posts() {Let’s create a dynamic route to handle displaying an individual post. Create a new file at `app/static/[id]/page.tsx` and populate with the following:```tsx title="app/static/[id]/page.tsx"-import supabase from "../../../utils/supabase";-import { notFound } from "next/navigation";+import supabase from '../../../utils/supabase'+import { notFound } from 'next/navigation'-export default async function Post({- params: { id },-}: {- params: { id: string };-}) {- const { data } = await supabase.from("posts").select().match({ id }).single();+export default async function Post({ params: { id } }: { params: { id: string } }) {+ const { data } = await supabase.from('posts').select().match({ id }).single()if (!data) {- notFound();+ notFound()}- return <pre>{JSON.stringify(data, null, 2)}</pre>;+ return <pre>{JSON.stringify(data, null, 2)}</pre>}```-Currently, this page is generated on-demand and then cached. This means the first person who visits the page will need to wait for the server to get the post data from Supabase. This won’t take long at all, because Supabase is Supa awesome! But, we can still make this *slightly* more efficient by telling Next.js a finite collection of paths that we want to generate at build time.+Currently, this page is generated on-demand and then cached. This means the first person who visits the page will need to wait for the server to get the post data from Supabase. This won’t take long at all, because Supabase is Supa awesome! But, we can still make this _slightly_ more efficient by telling Next.js a finite collection of paths that we want to generate at build time.-We do this by exporting out a `generateStaticParams` function from our dynamic StaticPost page.+We do this by exporting out a `generateStaticParams` function from our dynamic page.```tsx title="app/static/[id]/page.tsx"export async function generateStaticParams() {- const { data: posts } = await supabase.from("posts").select("id");+ const { data: posts } = await supabase.from('posts').select('id')return posts?.map(({ id }) => ({id,- }));+ }))}```@@ -188,100 +184,98 @@ export async function generateStaticParams() {The full component should look something like this:```tsx title="app/static/[id]/page.tsx"-import supabase from "../../../utils/supabase";-import { notFound } from "next/navigation";+import supabase from '../../../utils/supabase'+import { notFound } from 'next/navigation'export async function generateStaticParams() {- const { data: posts } = await supabase.from("posts").select("id");+ const { data: posts } = await supabase.from('posts').select('id')return posts?.map(({ id }) => ({id,- }));+ }))}-export default async function Post({- params: { id },-}: {- params: { id: string };-}) {- const { data: post } = await supabase.from("posts").select().match({ id }).single();+export default async function Post({ params: { id } }: { params: { id: string } }) {+ const { data: post } = await supabase.from('posts').select().match({ id }).single()if (!post) {- notFound();+ notFound()}- return <pre>{JSON.stringify(post, null, 2)}</pre>;+ return <pre>{JSON.stringify(post, null, 2)}</pre>}```Awesome! We now have a Supa snappy blog! The user never needs to wait for data to be fetched. All pages are statically generated at build time, and cached at CDN nodes close to our users! 🎉-Unfortunately, this means any changes we make in Supabase — adding, updating or deleting posts etc — will not be reflected in our blog. If we want to refresh this data on a regular basis, we need to tell Next.js when to *revalidate*.+Unfortunately, this means any changes we make in Supabase — adding, updating or deleting posts etc — will not be reflected in our blog. If we want to refresh this data on a regular basis, we need to tell Next.js when to _revalidate_.# Static with RevalidationBy exporting a `revalidate` variable from our component, we can specify how many seconds we consider this data to be “fresh”.```tsx-export const revalidate = 60;+export const revalidate = 60```+> This is similar to returning a `revalidate` key from the `getStaticProps` function in a component from the `pages` directory.+So, for 60 seconds Next.js will continue to respond with the static version of our page. After 60 seconds, it will fetch fresh data from Supabase and generate a new static page. However, there is no downtime while this happens, as the previous static page will continue to be served until the “fresh” one has been successfully generated.The `Posts` component should now look like this:```tsx title="app/static-with-revalidate/page.tsx"-import Link from "next/link";-import supabase from "../../utils/supabase";+import Link from 'next/link'+import supabase from '../../utils/supabase'-export const revalidate = 60;+export const revalidate = 60export default async function Posts() {- const { data: posts } = await supabase.from("posts").select("id, title");+ const { data: posts } = await supabase.from('posts').select('id, title')if (!posts) {- return <p>No posts found.</p>;+ return <p>No posts found.</p>}return posts.map((post) => (<p key={post.id}><Link href={`/static/${post.id}`}>{post.title}</Link></p>- ));+ ))}```And the `Post` component should look like this:```tsx title="app/static-with-revalidate/[id]/page.tsx"-import supabase from "../../../utils/supabase";-import { notFound } from "next/navigation";+import supabase from '../../../utils/supabase'+import { notFound } from 'next/navigation'-export const revalidate = 60;+export const revalidate = 60export async function generateStaticParams() {- const { data: posts } = await supabase.from("posts").select("id");+ const { data: posts } = await supabase.from('posts').select('id')return posts?.map(({ id }) => ({id,- }));+ }))}-export default async function Post({- params: { id },-}: {- params: { id: string };-}) {- const { data: post } = await supabase.from("posts").select().match({ id }).single();+export default async function Post({ params: { id } }: { params: { id: string } }) {+ const { data: post } = await supabase.from('posts').select().match({ id }).single()if (!post) {- notFound();+ notFound()}- return <pre>{JSON.stringify(post, null, 2)}</pre>;+ return <pre>{JSON.stringify(post, null, 2)}</pre>}```+We now get all the benefits of static — users not waiting around while data is fetched at request time — but we also get the benefits of dynamic data, as it is being refreshed on a regular basis.++Very cool! 😎+# DynamicIf we want fresh data to be fetched on every single request, we can simply set our `revalidate` value to `0`.@@ -289,107 +283,100 @@ If we want fresh data to be fetched on every single request, we can simply set o**Posts Component**```tsx title="app/server-rendered/page.tsx"-import Link from "next/link";-import supabase from "../../utils/supabase";+import Link from 'next/link'+import supabase from '../../utils/supabase'-export const revalidate = 60;+export const revalidate = 0export default async function Posts() {- const { data: posts } = await supabase.from("posts").select("id, title");+ const { data: posts } = await supabase.from('posts').select('id, title')if (!posts) {- return <p>No posts found.</p>;+ return <p>No posts found.</p>}return posts.map((post) => (<p key={post.id}><Link href={`/static/${post.id}`}>{post.title}</Link></p>- ));+ ))}```**Single Post Component**```tsx title="app/server-rendered/[id]/page.tsx"-import supabase from "../../../utils/supabase";-import { notFound } from "next/navigation";+import supabase from '../../../utils/supabase'+import { notFound } from 'next/navigation'-export const revalidate = 60;+export const revalidate = 0export async function generateStaticParams() {- const { data: posts } = await supabase.from("posts").select("id");+ const { data: posts } = await supabase.from('posts').select('id')return posts?.map(({ id }) => ({id,- }));+ }))}-export default async function Post({- params: { id },-}: {- params: { id: string };-}) {- const { data: post } = await supabase.from("posts").select().match({ id }).single();+export default async function Post({ params: { id } }: { params: { id: string } }) {+ const { data: post } = await supabase.from('posts').select().match({ id }).single()if (!post) {- notFound();+ notFound()}- return <pre>{JSON.stringify(post, null, 2)}</pre>;+ return <pre>{JSON.stringify(post, null, 2)}</pre>}```This is similar to exporting a `getServerSideProps` function from a component in the `pages` directory.+All this server stuff is great, but what if you want to use Supabase client-side? 🤔+# Client-sideThere are many use-cases where you need to use Supabase client-side:1. Authentication- Supabase Auth does a bunch of stuff behind the scenes — handling 3rd party OAuth flows, for example. This will break if you try to sign users in and out on the server.+ Supabase Auth does a bunch of stuff behind the scenes — handling 3rd party OAuth flows, for example. This will break if you try to sign users in and out on the server.2. Realtime- Supabase manage the awesome power of websockets on your behalf — something that is not yet solved with this new serverless world.--3. You prefer it … there is nothing wrong with this!+ Supabase manages the awesome power of websockets on your behalf — something that is not yet solved in this serverless world.- You do you!+3. You prefer it+ There is nothing wrong with this! You do you!-To use Supabase client-side, we need to tell Next.js that this is a client component. We do this by specifying the `use client` directive at the top of our component. This opts into a similar flow to the `pages` directory — the component is rendered on the server and hydrated client-side.+To use Supabase client-side, we need to tell Next.js that this is a [Client Component](https://beta.nextjs.org/docs/rendering/server-and-client-components#client-components). We do this by specifying the `use client` directive at the top of our component. This opts into a similar flow to the `pages` directory — the component is rendered on the server and hydrated client-side.-> The React team is [working on an awesome new hook called `use`](https://github.com/acdlite/rfcs/blob/first-class-promises/text/0000-first-class-support-for-promises.md#example-use-in-client-components-and-hooks), which will drastically simplify fetching data client-side, but for now, we still need to rely on the combination of `useState` and `useEffect`.+> The React team is [working on an awesome new hook called "use"](https://github.com/acdlite/rfcs/blob/first-class-promises/text/0000-first-class-support-for-promises.md#example-use-in-client-components-and-hooks), which will drastically simplify fetching data client-side, but for now, we still need to rely on the combination of `useState` and `useEffect`.Let’s implement client-side data fetching.```tsx title="app/client-side/page.tsx"-"use client";+'use client'-import { useEffect, useState } from "react";-import supabase from "../../utils/supabase";+import { useEffect, useState } from 'react'+import supabase from '../../utils/supabase'export default function ClientPosts() {- const [isLoading, setIsLoading] = useState(true);- const [posts, setPosts] = useState<any>([]);+ const [isLoading, setIsLoading] = useState(true)+ const [posts, setPosts] = useState<any>([])useEffect(() => {const fetchPosts = async () => {- const { data } = await supabase.from("posts").select();- setPosts(data);- setIsLoading(false);- };-- fetchPosts();- }, []);-- return isLoading ? (- <p>Loading</p>- ) : (- <pre>{JSON.stringify(posts, null, 2)}</pre>- );+ const { data } = await supabase.from('posts').select()+ setPosts(data)+ setIsLoading(false)+ }++ fetchPosts()+ }, [])++ return isLoading ? <p>Loading</p> : <pre>{JSON.stringify(posts, null, 2)}</pre>}```@@ -404,63 +391,63 @@ Let’s merge the two previous concepts and fetch the initial state of our posts**Server Component**```tsx title="app/realtime/page.tsx"-import supabase from "../../utils/supabase";-import RealtimePosts from "./realtime-posts";+import supabase from '../../utils/supabase'+import RealtimePosts from './realtime-posts'-export const revalidate = 0;+export const revalidate = 0export default async function Realtime() {- const { data } = await supabase.from("posts").select("*");- return <RealtimePosts serverPosts={data} />;+ const { data } = await supabase.from('posts').select('*')+ return <RealtimePosts serverPosts={data} />}```**Client Component**```tsx title="app/realtime/realtime-posts.tsx"-"use client";+'use client'-import { useEffect, useState } from "react";-import supabase from "../../utils/supabase";+import { useEffect, useState } from 'react'+import supabase from '../../utils/supabase'export default function RealtimePosts({ serverPosts }: { serverPosts: any }) {- const [posts, setPosts] = useState(serverPosts);+ const [posts, setPosts] = useState(serverPosts)useEffect(() => {- setPosts(serverPosts);- }, [serverPosts]);+ setPosts(serverPosts)+ }, [serverPosts])useEffect(() => {const channel = supabase- .channel("*")- .on(- "postgres_changes",- { event: "INSERT", schema: "public", table: "posts" },- (payload) => setPosts((posts: any) => [...posts, payload.new])+ .channel('*')+ .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'posts' }, (payload) =>+ setPosts((posts: any) => [...posts, payload.new]))- .subscribe();+ .subscribe()return () => {- supabase.removeChannel(channel);- };- }, [serverPosts]);+ supabase.removeChannel(channel)+ }+ }, [serverPosts])- return <pre>{JSON.stringify(posts, null, 2)}</pre>;+ return <pre>{JSON.stringify(posts, null, 2)}</pre>}```> `useEffect` is used to subscribe to changes to the `serverPosts` prop. Without this, our component would not display fresh server-side results when the parent component is re-rendered, only on the first render.--This is a great pattern for fetching initial data server-side and subscribing to realtime changes client-side. This will likely be replaced by the `use` hook once it is stable with Next.js — as it also uses suspense to *suspend* the rendering of a component while fetching data.+This is a great pattern for fetching initial data server-side and subscribing to realtime changes client-side. This will likely be replaced by the `use` hook once it is stable with Next.js — it also uses suspense to _suspend_ the rendering of a component while fetching data, and cleans up those loading and error states.# Conclusion-Next.js 13 Server Components and Suspense are awesome! Async components allow us to think about data fetching and caching as separate concerns — rather than specifying completely different data fetching functions like `getStaticProps` and `getServerSideProps`. If our caching requirements for a component change, we simply update the caching value, rather than refactoring our data fetching logic.+Next.js 13 Server Components are awesome! Suspense is awesome! Async components are awesome!-Allowing any component in the tree to be either a server or client component, that is responsible for its own data, and suspends rendering until it is ready, drastically simplifies our code, and provides much more flexible patterns for maintainable applications.+The combination of these concepts allow us to think about data fetching and caching as separate concerns, rather than specifying completely different data fetching functions like `getStaticProps` and `getServerSideProps`. If our caching requirements for a component change, we simply update the caching value, rather than refactoring our data fetching logic.++Additionally, by allowing any component in the tree to be either a server or client component — that is responsible for its own data and suspends rendering until it is ready — drastically simplifies our code, and provides much more flexible patterns for creating maintainable applications as complexity grows.# More Next.js 13 Resources+- [Next.js 13 Beta Docs](https://beta.nextjs.org/docs)- [Creating an authenticated Supabase client in Next.js 13 Server Component](https://github.com/supabase/auth-helpers/tree/main/examples/nextjs-server-components)- [Data fetching and caching with Next.js 13 - Supabase Happy Hour #26](https://www.youtube.com/watch?v=QH0P5xZt5wY)