Next.js Discord

Discord Forum

Using the axios instance created for the server side on the client side.

Unanswered
Dutch posted this in #help-forum
Open in Discord
DutchOP
I created an axios instance and I use it in api routes but i want to use it within the client component in useEffect - don't want to create a new api routes for that -
next/headers cookie has been using in axios instance but it doesn't work in client component . what should i do ?

instance.interceptors.request.use(
  async function (config) {
    const cookieStorage = await cookies();
    const token = cookieStorage.get(STATIC_KEYS.TOKEN)?.value;
    if (token) {
      config.headers['x-token'] = token;
    }

    return config;
  },
  function (error) {
    return Promise.reject(error);
  },
);


error
Ecmascript file had an error
  1 | import axios from 'axios';
> 2 | import { cookies } from 'next/headers';
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  3 | import { STATIC_KEYS } from '../constant';
  4 |
  5 | const options = {

You're importing a component that needs "next/headers". That only works in a Server Component which is not supported in the pages/ directory. Read more: https://nextjs.org/docs/app/building-your-application/rendering/server-components

10 Replies

DutchOP
should i use the api routes or create a new axios instance for client side ?
what is the best technique for such situations ?
@Dutch should i use the api routes or create a new axios instance for client side ?
Braconid wasp
In that case you should have separate axios instances, since one is using server-only stuff like cookies
DutchOP
ok but there will be 2 different instances with almost the same content , right ?
server instance will use next/header cookie and client instance will use document.cookie . what will be the benefit of that ?
i think it's just a bunch of code
@Dutch ok but there will be 2 different instances with almost the same content , right ?
Braconid wasp
you can move the shared part into a util
DutchOP
ok it's a good idea . but i curios that why don't you suggest the api routes instead ?
in this way , we can use server side instance of axios
Pacific sand lance
if you would like to use same axios instance both client side and server side, then you can create server action, which reads token from cookies and then in interceptor check if request was made server side