Skip to content
Discussion options

You must be logged in to vote

You can handle Axios requests compatible with both client and server in Next.js by checking the environment and retrieving the token accordingly.

Server-side (App Router / server function):

import axios from 'axios';
import { cookies } from 'next/headers';

export async function getDataServer() {
  const token = cookies().get('token')?.value;
  const res = await axios.get('https://api.example.com/data', {
    headers: { Authorization: `Bearer ${token}` },
  });
  return res.data;
}

Client-side (Browser):

import axios from 'axios';

export async function getDataClient() {
  const token = localStorage.getItem('token');
  const res = await axios.get('https://api.example.com/data', {
    headers

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by bbhxwl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
2 participants