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

Categories

0 votes
5.2k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...