Getting Started

Getting Started

⚠️

The package is not production ready, yet.

Install

Inside your Next.js project directory, run the following:

pnpm i @angora/fetch

Update config

Update next.config.js to add withAngoraFetch:

next.config.js
const { withAngoraFetch } = require('@angora/fetch/build');
 
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
};
 
module.exports = withAngoraFetch(nextConfig);

Middleware

Update or create middleware.js (or middleware.ts if you use TypeScript) to call setAngoraFetchHeaders:

middleware.ts
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
 
import { setAngoraFetchHeaders } from '@angora/fetch';
 
export async function middleware(req: NextRequest) {
  const res = NextResponse.next();
  await setAngoraFetchHeaders(req, res);
  return res;
}
 
export const config = {
  matcher: ['/((?!api|_next/static|favicon.ico|sw.js).*)'],
};

Provider

Update or create pages/_app.js (or pages/_app.tsx if you use TypeScript) to add AngoraFetchProvider:

pages/_app.tsx
import type { AppProps } from 'next/app';
 
import { NextAngoraFetchProvider } from '@angora/fetch';
 
export default function App({ Component, pageProps }: AppProps) {
  return (
    <NextAngoraFetchProvider>
      <Component {...pageProps} />
    </NextAngoraFetchProvider>
  );
}

That's it! You can now use it on any page

pages/index.tsx
import { getFetchHooks } from '@angora/fetch';
// Same rules as Next.js' `config` applies to the `angora` constant.
export const angora = {
  fetch: ['/api/hello-world'],
};
// `getFetchHooks` returns React.js hooks
// inspired by TanStack Query and SWR.
const [useHelloWorld] = getFetchHooks(angora);
 
type HelloWorldResponse = { greeting: string };
 
export default function HomePage() {
  const helloWorldData = useHelloWorld<HelloWorldResponse>();
  const { body, error, isFetching, isOK, status } = helloWorldData;
 
  if (isFetching) return <p>Loading...</p>;
  if (error) return <p>{error.message}</p>;
  if (!isOK) return <p>{status?.text ?? 'Oops!'}</p>;
 
  return <p>{body.greeting}</p>;
}

CodeSandbox

There is also a CodeSandbox that you can fork and start experimenting faster: https://codesandbox.io/p/sandbox/next-js-with-angora-fetch-example-z5m10e (opens in a new tab)