Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.8k views
in Technique[技术] by (71.8m points)

javascript - localStorage not defined using axios interceptor in NextJS

I have a file called api.js in my root directory which takes care of calls to the external API (request and response interceptors). I am using this to inject the access_token, so my request interceptor looks like so;

import axios from 'axios';

const api = axios.create({
    baseURL: process.env.NEXT_PUBLIC_API_URL
});

// Add request interceptor
api.interceptors.request.use(
    async config => {
        const token = localStorage.getItem('access_token');

        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token;
        }
        config.headers['Content-Type'] = 'application/json';
        config.headers['Accept'] = 'application/json';

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

In my pages directory, i have a file called users.js ... All i want to do is return the list of users from my external API and display it in a grid when the /users page is loaded. My users.js file currently looks like so;

import api from "../services/api"

export default function Users() {
    return (
        <div>
        </div>
    )
}

export async function getStaticProps() {
    const res = await api.get('/accounts');

}

But when I run this, i am getting the following error;

ReferenceError: localStorage is not defined

The error references the api.js file at the following line;

const token = localStorage.getItem('access_token');

I cant seem to figure out whats going on. Any help would be greatly appreciated


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are in server-side while executing fetch in getStaticProps() and localStorage doesn't exist in server side.So if you fetch data in client side the localStorage will not be undefined.

  • getStaticProps — fetches data at build time.
  • getStaticPaths — pre-render dynamic routes at build time.
  • getServerSideProps — fetches data on each request.
  • swr — fetches data from the Client at run time.

If you need to fetch data on the client, you must use swr.

import api from "../services/api"
const fetcher = url => api.get('/accounts'); // .then(res => res.data)

function Users() {
  const { data, error } = useSWR('/api/data', fetcher)
  // ...
}

Check this for swr.

Check this link for getStaticProps.

Also check this for more information about client side/server side fetch.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...