Reputation: 10412
I currently have existing Laravel backend which returns JWT token and setting this under signin callback with data.accessToken = data.access.token. I can also retrieve token and send to private endpoint with something like:
const [session] = useSession()
ApiClient.get(`${API_URL_PREFIX}/insert/data`, { headers: { Authorization: 'Bearer ' + session.accessToken }, params: params })
but this is only available within React hooks but I need to send this and I have axios call in another file with below code:
import axios from 'axios';
const env = process.env.NODE_ENV;
const dev = env !== 'production';
const apiHost = dev ? 'http://localhost:8000/' : '/';
const ApiClient = axios.create({ baseURL: '/' });
export { ApiClient, apiHost };
How can I get access token from this separate file and send it as a default header for every request using the API client?
Also is there any recommended approach for invalid request from the server? For example if I get 401, where can I catch this and redirect back to login page?
What are you trying to do Trying to send access token for every request from separate library and redirect to login page if not authenticated for private endpoint requests.
Reproduction Import axios, use credentials provider in Next Auth with custom backend returning JWT token. Map the result of JWT in signIn callback to data so it can be saved in the user session for retrieval later.
Feedback There seem to be lack of complete example in the docs with custom backend with credentials provider with private endpoint handling and retrieval, encapsulation of access token for the requests done in separate API request. It would be nice to have end to end example where we can reference implement handling all these scenarios.
Upvotes: 1
Views: 3277
Reputation: 224
I have written a post detailing how to use the credentials provider with a custom backend here
Regarding using a default header for all your requests I would suggest adding a custom React hook. You will be able to use the useSession() hook from nextauth.js in there and then you can use that custom hook for all the data fetching requirements.
Upvotes: 0