2

I'm struggling with calling my secure (secured by Auth0) backend API with the Auth0 Bearer token. I want to add the Bearer token to every request made to the API in my NextJs app. I can't find a solution for this anywhere

Method to retrieve accessToken

 import { getAccessToken } from "@auth0/nextjs-auth0";

 ...

 const { accessToken } = await getAccessToken(req, res, {
    scope: "...",
 });
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • I've used nuxt-auth (not to be confused) and it attaches auth headers on every axios request. I imagine package next-auth does the same. You'd just have to configure it to use auth0 provider –  Mar 15 '22 at 19:09
  • Or if you're using axios just use an interceptor –  Mar 15 '22 at 19:10
  • @Issayah Do you have an example of this? I tried things like this but that doesn't worked out for me. Should be doing something wrong. When I tried the interceptor I got an error message that I can't change the request. And also, I needed the `req` & `res` to retrieve the accessToken – Jesper van den Munckhof Mar 15 '22 at 19:18
  • Truth be told I enjoyed using nuxt-auth more. Many of the things that it did made better intercept code than I code have written, like automatically refreshing the access token. Try https://stackoverflow.com/questions/43051291/attach-authorization-header-for-all-axios-requests –  Mar 15 '22 at 19:20
  • Yeah I understand, Thanks for your fast reply. A link to a documentation would be nice too – Jesper van den Munckhof Mar 15 '22 at 19:23

1 Answers1

0

You can create an axios instance:

  import axios from "axios";
  import { getAccessToken } from "@auth0/nextjs-auth0";
  const instance = axios.create();
  // Intercept all requests on instance
  instance.interceptors.request.use(function (config) {
    return getAccessToken() // requires a Shopify App Bridge instance
         .then(({token}) => {
      // Append your request headers with an authenticated token
      config.headers["Authorization"] = `Bearer ${token}`;
      return config;
    });
  });
  export default instance;
Yilmaz
  • 35,338
  • 10
  • 157
  • 202