Docs
SSR

Server-Side Rendering

http-react supports server-side rendering out of the box. When you set a default value in useFetch, that data will be server-side rendered.

Using the Client API

Since useFetch doesn't work server-side, use the Client object to fetch data on the server. It provides an API similar to Axios (opens in a new tab) but uses fetch internally instead of XMLHttpRequest.

Traditional SSR (Next.js Pages Router)

Example using Next.js's getServerSideProps (opens in a new tab):

pages/my-page.tsx
import useFetch, { Client } from 'http-react'
 
// Create a reusable API client
const api = Client.extend({
  baseUrl: 'https://my-api.com',
  headers: {
    Authorization: 'Token etc'
  }
})
 
export async function getServerSideProps(context) {
  const { data } = await api.get('/api/user')
 
  return {
    props: {
      user: data
    }
  }
}
 
export default function MyPage({ user }) {
  const { data } = useFetch('/api/user', {
    default: user
  })
 
  return (
    <div>
      <h2>Welcome, {data.name}</h2>
    </div>
  )
}

React Server Components (Next.js App Router)

Server Components in Next.js 13+ work differently from client components. They don't ship JavaScript to the client and run server-only code, making them ideal for layouts and authentication.

Fetching Data in a Server Component

Inside your root layout (a Server Component):

app/layout.tsx
import { cookies } from 'next/headers'
import { FetchConfig, Client } from 'http-react'
import Login from 'components/Login'
 
export default async function Layout({ children }) {
  // Access cookies (server-only)
  const appSession = cookies().get('appSession')?.value
 
  // Create an API client
  const api = Client.extend({
    baseUrl: 'https://my-website.com/api',
    headers: {
      Authorization: 'Token ' + appSession
    }
  })
 
  // Fetch data on the server
  const { data, error } = await api.get('/auth')
 
  if (error) return <Login />
 
  return (
    <FetchConfig
      {...api.config}
      value={{
        'GET /api/profile': data // Pre-rendered data
      }}
    >
      {children}
    </FetchConfig>
  )
}

Accessing Pre-rendered Data in a Client Component

app/profile.tsx
'use client'
 
import useFetch from 'http-react'
 
export default function Profile() {
  const { data } = useFetch('/api/profile') // Data is already loaded!
 
  return (
    <div>
      <h2>Name: {data.name}</h2>
    </div>
  )
}

The data fetched in the Server Component is automatically available in the Client Component without an additional network request.