Cross-origin requests

Token-based authentication flow

If your client and server are on different origins (e.g. making an API call to a server on api.foo.com from JavaScript running on a client at foo.com), the session token needs to be passed in a network request header. There are a few different ways this can be done on the front-end.

Using Fetch with React

In order to pass the session token using the browser Fetch API, it should be put inside a Bearer token in the Authorization header. To retrieve the session token, use the getToken method from the useAuth() hook. Be mindful that getToken is an async function that returns a Promise which needs to be resolved.

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;
}

Using Fetch with OneAuxiliaJS

If you are not using React or Next.js, you can access the getToken method from the session property of the OneAxulia object. This assumes you have already followed the instructions on setting up OneAuxiliaJS and provided it with your Frontend API URL.

(async () => {
  fetch('/api/foo', { 
    headers: { 
      Authorization: `Bearer ${await oneAuxilia.session.getToken()}` 
    } 
   }).then(res => res.json());
})();

Last updated