Experiencing Compatibility Issues: Next.js 14.0.3 with next-auth and NestJS Backend Runs Smoothly in Development Environment, but Encounters

Currently, I am developing a Next.js 14.0.3 application that utilizes next-auth for authentication. The application interacts with an external NestJS backend for authorization and JWT validation. While everything functions correctly in the development environment (using npm run dev), I encounter an error during the production build process (using npm run build).

.next/types/app/api/auth/[...nextauth]/route.ts:8:13
Type error: The type 'OmitWithTag<typeof import("U:/sid/sid-front/app/api/auth/[...nextauth]/route"), "POST" | "GET" | "HEAD" | "OPTIONS" | "PUT" | "DELETE" | "PATCH" | "config" | "generateStaticParams" | "revalidate" | ... 5 more ... | "maxDuration", "">' does not meet the requirements of the constraint '{ [x: string]: never; }'.
  The property 'authOptions' is incompatible with the index signature.
    The type 'AuthOptions' cannot be assigned to 'never'.

The content of my [...nextauth]/route.ts file is as follows:

import { NextAuthOptions } from "next-auth";
import { JWT } from "next-auth/jwt";
import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";

async function refreshToken(token: JWT): Promise<JWT> {
  const res = await fetch(process.env.NEXT_PUBLIC_API_URL + "/auth/refresh", {
    method: "POST",
    headers: {
      authorization: `Refresh ${token.backendTokens.refreshToken}`,
    },
  });
  console.log("refreshed");

  const response = await res.json();

  return {
    ...token,
    backendTokens: response,
  };
}

export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: {
          label: "Email",
          type: "text",
          placeholder: "jsmith",
        },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials, req) {
        if (!credentials?.email || !credentials?.password) return null;
        const { email, password } = credentials;
        const res = await fetch(
          process.env.NEXT_PUBLIC_API_URL + "/auth/login",
          {
            method: "POST",
            body: JSON.stringify({
              email,
              password,
            }),
            headers: {
              "Content-Type": "application/json",
            },
          }
        );
        if (res.status == 401) {
          console.log(res.statusText);

          return null;
        }
        const user = await res.json();
        return user;
      },
    }),
  ],

  callbacks: {
    async jwt({ token, user }) {
      if (user) return { ...token, ...user };

      if (new Date().getTime() < token.backendTokens.expiresIn) return token;

      return await refreshToken(token);
    },

    async session({ token, session }) {
      session.user = token.user;
      session.backendTokens = token.backendTokens;

      return session;
    },
  },
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

In addition to the above code, here is my next-auth.d.ts file:

import NextAuth from "next-auth";

declare module "next-auth" {
  interface Session {
    user: {
      id: number;
      email: string;
      name: string;
    };
    backendTokens: {
      accessToken: string;
      refreshToken: string;
      expiresIn: number;
    };
  }
}

import { JWT } from "next-auth/jwt";

declare module "next-auth/jwt" {
  interface JWT {
    user: {
      id: number;
      email: string;
      name: string;
    };
    backendTokens: {
      accessToken: string;
      refreshToken: string;
      expiresIn: number;
    };
  }
}

Answer №1

I organized the authOptions and refreshToken functions into their own file, exported them, and then successfully imported them into route.ts to fix the issue.

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

The data table fails to display updated information from the data source

After updating the data-array (FileDto), I am unable to see any changes reflected in the Datatable. I have tested outputting the data using ngFor, and it works perfectly fine. Here is the HTML code: <ngx-datatable class="material striped" [rows]= ...

In search of assistance with resolving a React Typescript coding issue

I need help converting a non-TypeScript React component to use TypeScript. When attempting this conversion, I encountered the following error: Class 'Component' defines instance member function 'componentWillMount', but ext ...

What is the best way to modify the color of a table cell in Typescript with *ngFor loop?

I have an image located at the following link: https://i.sstatic.net/rxDQT.png My goal is to have cells with different colors, where main action=1 results in a green cell and action=0 results in a red cell. Below is the HTML code I am working with: & ...

What are the steps for utilizing joi for validating an email address?

I need assistance with implementing validation using the joi npm package. How can I set up a route for users to register and login without using ejs or html? Additionally, how do I create a protected route? const express = require("express"); c ...

Is Firebase billing impacted by NextAuth integration?

Currently, I am utilizing NextAuth in conjunction with Firebase Auth as an adapter for authentication. This setup is particularly useful for authenticating my admin users exclusively on specific pages. My understanding is that NextAuth monitors the session ...

NextJS is throwing an Uncaught TypeError because it is unable to read properties of undefined, specifically the 'attributes'

Whenever I attempt to include the type attribute within the <input> tag in NextJS, I encounter this error message while using the following function. const InputComponent = ({value, prefix, id, placeholder, autoCompleteLabel}: InputComponentProps) = ...

How can you toggle the selection of a clicked element on and off?

I am struggling with the selection color of my headings which include Administration, Market, DTA. https://i.stack.imgur.com/luqeP.png The issue is that the selection color stays on Administration, even when a user clicks on another heading like Market. ...

add headers using a straightforward syntax

I'm attempting to append multiple header values. This is what I'm currently doing: options.headers.append('Content-Type', 'application/json'); options.headers.append('X-Requested-By', 'api-client'); ... ...

Is a function repeatedly invoked?

I have implemented a Pagination component in NextJS as follows: import Pagination from 'react-bootstrap/Pagination'; import Router from "next/router"; import {useEffect} from "react"; export { Paging } function Paging(props) ...

Passing RxJs pipes as a parameter

Is there a way to pass pipes as parameters? For example: var mypipes = [ pipeA(() => { alert("a"); }), pipeB(() => { alert("b"); }) ...

Want to know how to center the value of a slider range input in your React project using NextJS and Tailwind

Can someone help me with the issue I'm having with the offset? Is there a way to link a value to the thumb? I've tried two methods, but one gives a significant offset and the other gives less. However, it seems more like a workaround than a solu ...

Using Typescript to pass a property as one of the keys in an object's list of values

In my React Native project, I need to pass a string value from one component to another. The different options for the value can be found in the ScannerAction object: export const ScannerAction = { move: 'move', inventory: 'inventory&apo ...

What causes the variation in typing behavior between specifying props directly on a component versus nesting them inside another prop?

Understanding the next component might be a bit tricky, so let's delve into it (Check playground): type Props<T> = { initValue: T, process: (value: T) => T } export const Input = <T,>({ initValue, process, }: Props<T>): ...

Saving JSON format in VueX State Management

I'm relatively new to using Vue/VueX and I am exploring methods for storing JSON data in the VueX state. Initially, it seemed like a simple task: state { jsonthing: { ... } } However, I encountered an issue where getters return an Observer type ins ...

Table of contents not working on Vercel, yet functions properly on localhost

I'm struggling to incorporate a dynamic table of contents into my blog page on next.js. The code functions perfectly on my local server, but upon deploying it to Vercel, I encounter the following error: TypeError: Cannot read properties of undefined ( ...

Finding the root directory of a Node project when using a globally installed Node package

I've developed a tool that automatically generates source code files for projects in the current working directory. I want to install this tool globally using npm -g mypackage and store its configuration in a .config.json file within each project&apos ...

Supabase: Retrieving a single object from a query instead of an array

Can anyone shed light on why the supabase query below is returning an Object rather than an Array? export async function getStaticProps() { var today = new Date(); today = today.toISOString().split('T')[0]; const { books, error } = a ...

The issue encountered during a POST request in Postman is a SyntaxError where a number is missing after the minus sign in a JSON object at position 1 (line 1

Running my API in a website application works flawlessly, but encountering SyntaxError when testing it in Postman - specifically "No number after minus sign in JSON at position 1" (line 1 column 2). The data is correctly inputted into the body of Postman a ...

Using TypeScript to pass the text field ID to a function for clearing the text field with a button

I am looking for a way to improve the functionality of my web page featuring several buttons that will clear different text boxes on the same line. Currently, I am using separate functions for each button, but my goal is to streamline this process by utili ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...