The issue of session type not updating in Next.js 14 with Next-auth 5 (or possibly version 4) is a common concern that needs to

Experimenting with new tools, I encountered an issue when trying to utilize the auth() function to access user data stored within it. TypeScript is indicating that the user does not exist in Session even though I have declared it. Here is my auth.ts file:

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { authConfig } from "./authconfig";
import { connectDb } from "./lib/utils";
import { User } from "./lib/models";
import bcrypt from "bcrypt";
import { UserType } from "./lib/types";

declare module "next-auth" {
  interface Session {
    user?: UserType;
  }
}

declare module "next-auth" {
  interface User {
    username: string;
    img: string;
  }
}

const login = async (credentials: Partial<Record<string, unknown>>) => {
  try {
    connectDb();
    const user = await User.findOne({ username: credentials.username });

    if (!user) throw new Error("Invalid credentials");

    const isPasswordCorrect = await bcrypt.compare(
      credentials.password as string,
      user.password
    );

    if (!isPasswordCorrect) throw new Error("Invalid credentials");

    return user;
  } catch (error) {
    console.log(error);
    throw new Error("Login failed");
  }
};

export const { signIn, signOut, auth } = NextAuth({
  ...authConfig,
  providers: [
    CredentialsProvider({
      async authorize(credentials) {
        try {
          const user = await login(credentials);
          return user;
        } catch (error) {
          return null;
        }
      },
    }),
  ],
  callbacks: {
    async session({ session, user }) {
      if (session.user) {
        session.user.username = user.username;
        session.user.img = user.img;
      }
      return session;
    },
  },
});

And here is where the auth() function is executed:

import { MdLogout } from "react-icons/md";
import styles from "./sidebar.module.scss";
import MenuLink from "./menuLink/menuLink";
import Image from "next/image";
import { MENU_ITEMS } from "@/app/data/menuItems";
import { auth, signOut } from "@/app/auth";
import { authProvider } from "./authProvider";

const Sidebar = async () => {
  const { user } = await auth();
  return (
    <div className={styles.container}>
      <div className={styles.user}>
        <Image
          className={styles.userImage}
          priority
          src={user?.img || "/noavatar.png"}
          alt=""
          width="50"
          height="50"
        />
        <div className={styles.userDetail}>
          <span className={styles.username}>{user?.username}</span>
          <span className={styles.userTitle}>Administrator</span>
        </div>
      </div>
      <ul className={styles.list}>
        {MENU_ITEMS.map((category) => (
          <li key={category.title}>
            <span className={styles.category}>{category.title}</span>
            {category.list.map((item) => (
              <MenuLink item={item} key={item.title} />
            ))}
          </li>
        ))}
      </ul>
      <form
        action={async () => {
          "use server";
          await signOut();
        }}
      >
        <button className={styles.logout}>
          <MdLogout />
          Log out
        </button>
      </form>
    </div>
  );
};

export default Sidebar;

Despite declaring the user object in Session, TypeScript still raises an error stating: Property 'user' does not exist on type 'Session | null'. Can anyone advise on how to resolve this issue?

Answer №1

It's possible that the value of `session` is null, which could lead to errors if you try to access `session.user`.
In cases where you encounter the error message:</p>
<blockquote>
<p>Property 'user' does not exist on type 'Session | null'</p>
</blockquote>
<p>You can resolve this issue by using <code>session?.user
instead.

Answer №2

After many attempts, I finally succeeded in achieving my goal: Here is the content of my /src/app/lib/type/auth.d.ts:

import type { MY_CUSTOM_TYPE } from 'MY_PATH'

import 'next-auth'

declare module 'next-auth' {
  interface User extends MY_CUSTOM_TYPE {}
}

Previously, I neglected to import 'next-auth' which caused issues. Now that I have imported it, I can access the variable session.user.organizationId using useSession() or auth(), for example. This variable is defined in MY_CUSTOM_TYPE and TypeScript no longer raises any complaints.

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

`Firebase User Instance and Custom Firestore Document`

Recently, I posted a question regarding Google Firebase Angular Firestore switchMap and encountered some issues. The question can be found here. After exploring AngularFireAuth, I learned that it is used to create a User object with fixed values, requirin ...

The configuration of the leaflet in Nextjs seems to be malfunctioning

I am facing an issue while trying to integrate a customizable map on my website using React Leaflet. The map appears visible, but the tiles are cut off in different sections marked as "leaflet-tiles". It's causing some display problems that ...

Strategies for updating JSON file content as data evolves

I am facing an issue with loading a json file that populates charts. The file is generated from external data sources and stored in the asset directory. Is there a method to automatically load the updated json file? I have attempted to include the code fo ...

Comparing JSON import methods: HTTP vs require

I discovered two methods for importing local json files into my code. Using angulars http get. This method is well-known for loading json input. It provides the flexibility to easily switch between remote and local json files. Typescript require Anot ...

Is there a way to drop a pin on the Google Maps app?

Is there a way to pinpoint the specific location on Google Maps? <google-map id="map-container" width="100%" height="100%" class="maps"></google-map> ...

Unlocking the Power of Data Passing Through Tabs

My Application Structure Client Module - Material Tab Tab 1 - Customer Table View Tab 2 - Edit Customer View <mat-tab-group> <mat-tab label="View"> <div> <app-customer-table></app-customer-table> & ...

How can I implement a scroll bar in Angular?

I am facing an issue with my dialog box where the expansion panel on the left side of the column is causing Item 3 to go missing or appear underneath the left column when I expand the last header. I am looking for a solution to add a scroll bar so that it ...

Guide to adding a Favicon Icon to a Next Js 13 App Router

Is it possible to update the favicon icon in Nextjs 13 by utilizing the app router for routing? ...

What is the reason TypeScript does not recognize the type when dealing with promises?

I am encountering an unexpected behavior where there is no error even though there should be one in TypeScript when using promises. I assigned a number value to a string variable, but surprisingly, no error was thrown. Why does this happen? https://codesa ...

Updating the state in React Native does not occur

I'm facing an issue where I can't seem to update the state using useState while coding in React Native. The component in question is a styled TextInput named SearchField. Can anyone help me figure out what I might be doing wrong that's preve ...

Is it possible to extract a single element from an array that is stored as a standard Observable?

Currently, I am using a regular observable instead of an observableArray. This observable keeps an array of elements which is defined as follows: public arrayOfItems: IArrayItem[]; public arrayOfItems$: BehaviorSubject<IArrayItem[]> = new BehaviorSu ...

Angular: Connecting template data to different visual presentations

Looking for a solution to display data and map values to another presentation without needing complex ngIf statements or creating multiple components. Check out this sample: https://stackblitz.com/edit/angular-9l1vff The 'vals' variable contain ...

When the key property is utilized, the state in react useState is automatically updated; however, for updating without it, the useEffect or a

I am working on a component that looks like this: import React, { useState } from "react"; import { FormControl, TextField } from "@material-ui/core"; interface IProps { text?: string; id: number; onValueChange: (text: stri ...

Compiling Vue with TypeScript: Troubleshooting common errors

Using Vue Components with Templates Multiple Times in TypeScript I am working on utilizing a component with a template multiple times within another component. The code is split between a .html file and a .ts file. The .html file structure is as follows: ...

When attempting to utilize SSR Portals with Next.js, an error may occur if the portals

My Next.js application is experiencing a random fatal error that necessitates restarting Node to resolve. The compressed error points to this URL: https://reactjs.org/docs/error-decoder.html/invariant=257 Oddly, I do not incorporate Portals anywhere in m ...

Error: It seems that the function (0 , _redux_slices_loginAuthApiSlice__WEBPACK_IMPORTED_MODULE_4__.useLoginMutation) is not a valid function or the value it returns is not iterable

Need help with resolving an issue in NextJS 14. Please guide me if I am doing anything wrong. Here are the package versions: "@reduxjs/toolkit" : "^2.0.1", "next" : "^14.0.4", "react" : "^18", "react-dom" : "^18", "react-redux" : " ...

To successfully import files in Sveltekit from locations outside of /src/lib, make sure to include the .ts extension in the import statement

Currently, I am working on writing tests with Playwright within the /tests directory. I want to include some helper functions that can be placed in the /tests/lib/helpers folder. When the import does not specifically have a .ts extension, tests throw a mo ...

Auth.js and Next.js, route error with callback handling

When deploying the app on a server using auth.js with credentials provider, an error is encountered. Interestingly, there are no errors when running the app on localhost. The login page structure can be seen below: 'use client' import { Label } ...

The 'innerText' property is not found in the 'Element' type

Currently, I am working with Typescript and Puppeteer. My goal is to extract the innerText from an element. const data = await page.$eval(selector, node => node.innerText); However, I encountered an error: The property 'innerText' is not ...

Unable to find the <a> element with a numerical id attribute in Playwright. The selector '#56' is not recognized as valid

Seeking to identify and target the <a> element with an id attribute. Attributes that may be used: role href title id style onclick I am able to do so using role and name, but unsuccessful with id or onclick. The latter two would be beneficial for f ...