Dealing with header types in Axios and Typescript when using Next.js

I successfully set up a next.js application with JWT authentication connected to a Spring Boot API (Next is used as a client). The implementation of the next.js app was influenced by this tutorial:

Key Dependencies: Axios: 0.24.0 Next: 12.0.7 React: 17.0.2 SWR: 1.1.0

In a page like [id].tsx, I utilize axios to make a request

const headers = api.defaults.headers;
const fetcher = (url: string) => axios.get(url, {headers}).then(res => res.data)

const router = useRouter()
const { id } = router.query
const path = process.env.API_URL + "events/" + id;
const { data } = useSWR<EventType>(path, fetcher);

... the rest of the component uses "data"...and after the component...

export async function getStaticPaths() {
  return {
    paths: [
      '/events/[...id]',
    ],
    fallback: true,
  }
}

export default EventPage;

When dealing with "headers," I encountered a TypeScript error:

(property) AxiosRequestConfig<any>.headers?: AxiosRequestHeaders
Type 'HeadersDefaults' is not assignable to type 'AxiosRequestHeaders'.
Index signature for type 'string' is missing in type 'HeadersDefaults'.ts(2322)
index.d.ts(68, 3): The expected type comes from property 'headers' which is declared here on type 'AxiosRequestConfig<any>'

There is an api.ts file that creates the axios object used for all requests in the app

import Axios from "axios";

const api = Axios.create({
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    }
});

export default api;

This api is imported in [id].tsx

And the Authorization context is established in auth.tsx

import React, { createContext, useState, useContext, useEffect } from 'react'
import { useRouter } from "next/router";
import LoadingPage from '../pages/loading';
import api from '../services/api';

const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {

    const [loading, setLoading] = useState<boolean>(true)

    useEffect(() => {
        async function loadUserFromStorage() {
            const token = window.localStorage.getItem('jwtAuthToken')
            if (token) {
                api.defaults.headers['Authorization'] = `Bearer ${token}`
            }
            setLoading(false)
        }
        loadUserFromStorage()
    }, [])

    return (
        <AuthContext.Provider value={{ loading }}>
            {children}
        </AuthContext.Provider>
    )
}


export const useAuth = () => useContext(AuthContext)

export const ProtectRoute = ({ children }) => {
    const auth = useAuth();
    const router = useRouter();
    if (
        (auth.loading && router.pathname !== '/') ||
        (router.pathname !== '/' && !window.localStorage.getItem('jwtAuthToken'))
    ) {
      return <LoadingPage />; 
    }
    return children;
  };

The "auth.loading" also presents a type error that I am currently working on resolving.

All of these configurations are applied to the _app.js:

function MyApp({ Component, pageProps }) {
  return (
    <AuthProvider>
      <ProtectRoute>
        <Component {...pageProps} />
      </ProtectRoute>
    </AuthProvider>
  );
}

Everything functions properly in development mode, but I am encountering difficulties when trying to build due to the type errors.

Answer №1

After poring over the index.d.ts file in the axios node_modules directory, I finally cracked the code. I realized that I needed to tweak my approach when making GET requests (for every page) and DELETE requests (for every material-ui card with a delete icon). The issue stemmed from not including the necessary headers in my POST and PUT requests, which caused the type to change when passing headers as props to forms.

const headers = api.defaults.headers.get;

To ensure compatibility, it's essential to specify the method in the request. Additionally, when dealing with auth.loading in auth.tsx file:

const AuthContext = createContext<{loading: boolean}>({loading: false});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for creating accurate types for my package?

Currently, I am in the process of creating an npm package to be used by other developers within my company. While most aspects are functioning smoothly, I am facing challenges with getting the declarations right. I have experimented with various methods f ...

Include a new module in the declarations NgModule utilizing ts-morph

Currently, I am utilizing the ts-morph library and my objective is to add a new component to the declarations: This is my initial setup: @NgModule({ declarations: [], imports: [], providers: [], }) Here is what I am aiming for: @NgModule({ declarations: [ ...

Utilize the CSS class or variable within an Angular TypeScript file for enhanced styling and functionality

Is it possible to utilize the scss class or variable in a typescript file? scss .thisIsGreen { color: green; } .thisIsBlue { color: blue; } Alternatively, you can use $thisIsGreen { color: green; } $thisIsBlue { color: blue; } Now, I want to ...

The Angular 2 router is not compatible with using the same component but with different IDs

Currently utilizing the alpha8 router with 3 main routes: export const appRoutes: RouterConfig = [ { path: '', component: LandingComponent }, { path: 'blog', component: BlogComponent }, { path: 'posts/:id', compon ...

Issue: Attempting to assign a 'boolean' variable to a type of 'Observable<boolean>' is not compatible

I am currently working on the following code: import {Injectable} from '@angular/core'; import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router'; import {Observable} from 'rxjs' ...

Issue found within triggered hook: "TypeError: Unable to retrieve property '$http' as it is undefined"

Hey there, I've created a userInfo() function to fetch user data and utilize it in different areas. How can I effectively call this function to retrieve the necessary information? Can anyone assist me with this issue? export function getUserInfo () { ...

Using NextJS to pass a string from an input field to getStaticProps via context

I am a beginner in NextJS and React, so please forgive my lack of knowledge. I am trying to figure out how to pass the text input by users from an input field (inside Header) to the getStaticProps function of a specific page using the React context API. I ...

The element is implicitly given an 'any' type due to the fact that a string expression cannot be used to index the following type: { "1" : { "key": string}; "2" : { "key": string};}

I have a JSON file containing IDs as keys like this: "1" : { "key": "value"}, "2" : { "key": "value"}, In my class, I import this JSON file as a data object and then use the ID passed to a method ...

Encountering an issue with importing typeDefs in Apollo Server (Typescript) from an external file

I decided to move the typeDefs into a separate file written in typescript and then compiled into another file. Upon doing so, I encountered the following error: node:internal/errors:490 ErrorCaptureStackTrace(err); ^ Error [ERR_MODULE_NOT_FOUND]: Una ...

Error message encountered in NextJS: Prop type validation failed for the `href` prop in the `<Link>` component. It should be a `string` or an `object`, but it was found to be `undefined

I'm trying to implement a header layout in my project, but I encountered an error. The error message states: "Failed prop type: The prop href expects a string or object in <Link>, but got undefined instead. Open your browser's console to vi ...

The Ultimate Guide to Converting Enums to Object Types using Typescript

Imagine having an enum declared as follows: enum CustomerType { New = 'new', Owner = 'self', Loyal = 'subscriber' } Utilizing this enum can simplify checks like: if(customer.type === CustomerType.New) What is the re ...

What is the process for utilizing SWR to display information from a GraphQL Apollo Server within a NextJS application?

While I can successfully access my GraphQL query using apollo-graphql-studio, and the resolver is configured correctly, I am facing difficulty in rendering the data. Being aware of the performance benefits of swr react-hook in next-js, I intend to fetch d ...

The initial render of Keen-slider in NextJS can sometimes encounter difficulties when using server-side rendering

While incorporating the keen-slider library v5.4.0 into my nextJS project with TypeScript, I encountered a peculiar issue. The error arises when the keen-slider is initially loaded for the first time, resulting in mismatched transform types causing items ...

Exploring ways to establish communication between parent and child components through click events

I am currently working on an Angular 8 application that involves a parent-child relationship. The parent component, DossierCorrespondenceComponent, contains a function that needs to be triggered from within the child component. This is the function in th ...

Having trouble changing the query string in the URL with Angular 4?

My search form includes various filters such as text inputs, checkboxes, and radio buttons. Whenever the user interacts with these filters, the query string in the URL needs to be updated. Consider the following scenario: http://example.com/search?myFilt ...

Next.js: Utilizing separate environment files for various environments

Here's the content of my package.json file: "scripts": { "dev": "next dev", "build": "next build", "start": "next start", }, In my next.config.js file, the console.log ...

redux-saga 'call' effect fails to properly type saga parameters

My saga is defined as follows: type GenericFunction = (...args: any[]) => any; interface IFetchSaga<T extends GenericFunction> { saga: T, args: Parameters<T> } function* triggerChange<T extends GenericFunction>(fetchSaga: IFetchS ...

When trying to update a form field, the result may be an

Below is the code for my component: this.participantForm = this.fb.group({ occupation: [null], consent : new FormGroup({ consentBy: new FormControl(''), consentDate: new FormControl(new Date()) }) }) This is th ...

Tips for launching Nx serve in debug mode for Angular using VSCode

When running my Angular Nx project in the VSCode debugger, I encounter an issue with using yarn. yarn start successfully executes the nx serve command when run from a terminal. However, the same yarn start command fails when executed through VSCode debug ...

Deactivate automatic logins following a password reset with the clerk tool

Looking for help with implementing a "forgot password" feature in my Next.js project using Clerk. I've been following the official documentation provided by Clerk, but ran into an issue where users are automatically logged in after resetting their pas ...