Same-origin requests

Session based authentication flow

Same-origin requests

If your client and server are on the same origin (e.g. making an API call to foo.com/api from JavaScript running on foo.com), the session token is automatically passed to the backend in a cookie. This means that all requests to same-origin endpoints are authenticated by default.

Using Fetch

You can use the native browser Fetch API as you normally would and the request will be authenticated.

fetch('/api/foo').then(res => res.json());

Background fetching

For applications that are fetching content in the background, like when a tab is no longer focused, you will need to include an Authorization header along with your request.

import { useAuth } from '@oneauxilia/nextjs';

export default function useFetch() {
  const { getToken } = useAuth();

  const authenticatedFetch = async (...args) => {
    return fetch(...args, {
      headers: { Authorization: `Bearer ${await getToken()}` }
    }).then(res => res.json());
  };
  return authenticatedFetch;
}

Last updated