Next.js has become one of the most popular frameworks for building React applications due to its powerful features like server-side rendering (SSR), static site generation (SSG), and API routes. To handle data fetching efficiently, combining Next.js with libraries like TanStack Query (formerly React Query) and Supabase can significantly enhance your development experience.In this guide, you'll learn how to use TanStack Query with Supabase to fetch and manage data seamlessly in a Next.js application. From setting up your project to handling SSR, we’ve got you covered!
Why Use TanStack Query and Supabase?
TanStack Query simplifies state management for asynchronous data, handling features like caching, background updates, and synchronization with minimal boilerplate. Combined with Supabase, an open-source backend-as-a-service platform, you can achieve efficient and type-safe data fetching with ease.
Key Benefits:
- Automatic caching and background updates.
- Out-of-the-box support for SSR and SSG in Next.js.
- Seamless integration with Supabase’s real-time features.
Prerequisites
This guide assumes you have:
- Basic knowledge of React and Next.js.
- A Next.js project set up (version 14.0.3 or later).
- A Supabase account. Create one here if you don’t have one.
Installing Dependencies
To get started, install the required packages:
npm install @supabase/supabase-js @tanstack/react-query @supabase/ssr @supabase-cache-helpers/postgrest-react-query
Setting Up React Query
Create a React Query client and wrap your application with the QueryClientProvider. This ensures the query state is accessible throughout your app.
'use client' import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { useState } from 'react'; export const ReactQueryClientProvider = ({ children }) => { const [queryClient] = useState(() => new QueryClient({ defaultOptions: { queries: { staleTime: 60000 } } })); return {children}; };
Database Setup
Create a countries table in your Supabase database:
create table countries ( "id" serial primary key, "name" text ); insert into countries (id, name) values (1, 'United Kingdom'), (2, 'United States'), (3, 'Singapore');
Generating TypeScript Types
Use the Supabase CLI to generate TypeScript types:
supabase login supabase init supabase link supabase gen types typescript --linked --schema=public > utils/database.types.ts
Creating Supabase Clients
Set up both client and server Supabase clients to manage data fetching:
// Client Supabase Client import { createBrowserClient } from '@supabase/ssr'; export default function useSupabaseBrowser() { return createBrowserClient( process.env.NEXT_PUBLIC_SUPABASE_URL, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ); } // Server Supabase Client import { createServerClient } from '@supabase/ssr'; export default function useSupabaseServer(cookieStore) { return createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY, { cookies: cookieStore } ); }
Server-Side Data Fetching
To fetch data server-side with React Query, use the prefetchQuery function:
import { dehydrate, QueryClient } from '@tanstack/react-query'; export default async function getServerData(params) { const queryClient = new QueryClient(); await queryClient.prefetchQuery('countries', fetchCountries); return { props: { dehydratedState: dehydrate(queryClient) } }; }
Client-Side Data Fetching
For client-side fetching, leverage React Query’s useQuery hook:
'use client'; import { useQuery } from '@tanstack/react-query'; import useSupabaseBrowser from './utils/supabase-browser'; export default function Countries() { const supabase = useSupabaseBrowser(); const { data, isLoading } = useQuery('countries', () => supabase.from('countries').select('*')); if (isLoading) returnLoading...;
{data.map((country) =>
return
- {country.name}
Conclusion
Using TanStack Query with Supabase unlocks powerful possibilities for building robust and efficient Next.js applications. From automatic caching to seamless SSR integration, these tools make managing data effortless. Give it a try and watch your productivity soar!