What is the reason behind the auth() function in Auth.js returning a null user object?

Utilizing Auth.js credentials provider for user sign-ins in a Next.js application has proven successful. The auth() function now returns a non-null object upon signing in, as opposed to returning null previously.

// when not signed in
const session = await auth();
console.log(session)
// null

// when signed in
const session = await auth();
console.log(session)
// { user: {}, expires: '2024-07-28T14:03:13.208Z' }

I'm curious about the fact that the user object is empty {} and wonder what it should actually contain. It's possible that my expectations are off due to not fully grasping the underlying patterns at play here.

Access to the project's database is indirect for me, as I need to interact with a specific API endpoint. The returned data from the API is somewhat obscured for the sake of brevity.

{
  result: { status_code: 0, status: 'Ok', message: 'Sign in' },
  payload: {
    data: {
      auth: [Object],
      refresh_token: [Object],
      user: [Object],
      project: [Object]
    }
  }
}

The auth and refresh_token properties hold bearer and refresh tokens respectively. Meanwhile, the user and project properties contain the user-related information I seek.

How are these properties linked to the session? What is the expected relationship between them? Isn't the 'user' essentially the 'session'? My assumption is that the user property from the result of auth() should encompass all user information along with references to bearer and refresh tokens for use in subsequent API calls.

Alternatively, could it be that I'm misinterpreting the patterns and concepts at play here?

Provided below is the auth.ts file:

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut
} = NextAuth({
  session: {
    strategy: "jwt",
  },
  providers: [
    CredentialsProvider({
      async authorize(credentials){
        try {
          const login = await fetch(`https://some_project/login`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(credentials),
          });
          const user = await login.json();
          console.log(user);
          return user;
        } catch (error) {
          throw new Error("")
        }
      }
    })
  ]
})

In essence, how do the user objects returned in the above code snippet and the user object within the session correlate?

Answer №1

There may be a likelihood that the user object within the authorize function includes sensitive information that should not be shared with the client, possibly including credentials. For more details, you may want to check out this discussion on GitHub: User object is empty#2762

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

Using Next.js 9 to incorporate a third party CSS plugin

I'm looking to incorporate the owl.carousel plugin into a specific component without having to import the owl.carousel.css globally in the _app.js file. The plugin's CSS file is quite large and I only want to include it in the component where it ...

Secure your React TypeScript applications with GraphQL authentication

When users try to log in on my website, I need to verify their authentication using data from a GraphQL API. I referred to this tutorial for guidance: https://www.apollographql.com/docs/react/networking/authentication/ In my GraphQL playground, I execute ...

Is it possible to integrate Firebase Storage into a TypeScript/HTML/CSS project without the use of Angular or React?

For my project, I am aiming to create a login and register page using TypeScript. Currently, my code is functioning well even without a database. However, I would like to implement Firebase for storing user credentials so that the login process becomes mor ...

Exploring the concept of object inheritance in Angular 5 with Typescript

I'm facing a challenge related to inheritance while building my initial angular 5 application. The error message I encounter is: Property 'message' does not exist on type 'CouponEvent', as reported by the angular-cli. export class ...

Utilizing Vue 3 props validation in conjunction with the power of Typescript

Looking to customize a Link component using Nuxt, Typescript, and the composition-api. The prop target can accept specific values as outlined below. I'm curious if using a custom validator function to check prop types at runtime adds value when compar ...

Fire the BehaviorSubject with the identical value following a mutation

I am working with a BehaviorSubject where I have to make changes through mutation (for reasons beyond my control). I need to trigger the BehaviorSubject for subscriptions whenever there are changes. Is there another approach I can take instead of using: ...

What are the methods for providing both successful and unsuccessful promises, with or without data?

Seeking guidance on how to return a promise and an object named output before or after the $http call in AngularJS, specifically using Typescript. How can I ensure it works correctly? topicNewSubmit = (): ng.IPromise<any> => { var self = t ...

Using the TypeScript NextPage function along with the getInitialProps static method and @typescript-eslint/unbound-method

After enabling typescript-eslint with its recommended settings, I encountered an issue in my code. I came across this helpful post on Stack Overflow: Using getInitialProps in Next.js with TypeScript const X: NextPage = props => {/*...*/} X.getInitialP ...

Develop a series of sequential tests for the playwright to execute

Can someone assist me with my code? I am attempting to write a test in Playwright that navigates to the forgot password page, creates a new password, and then tries to log in using that new password. However, I am encountering an issue with retrieving the ...

When attempting to utilize expo-av in a React-Native project on iOS, the recorded MP4 file encountered an issue when trying to submit it as form data for Open

I've been working tirelessly through the night, trying to record myself on my iPhone using expo-av to capture speech and then upload it to openai's transcriptions endpoint with the whisper-1 model. The recording is saved as an mp4 file, which I ...

What could be causing TypeScript to display errors in unexpected locations while inferring inner types?

I encountered a rather intricate issue that's challenging to sum up in a brief title, my apologies for that. I devised a function that accepts a generic params type and returns a result type constructed from the params type. It utilizes string literal ...

Angular 2 error: "unknown element" issue persists despite exhausting all attempted solutions

Here's a typical scenario where I attempt to incorporate a component from another module : External component : import { Component, ViewEncapsulation, ElementRef, ViewChild, Input, Output, EventEmitter } from '@angular/core'; declare ...

Tips for effectively managing index positions within a dual ngFor loop in Angular

I'm working on a feedback form that includes multiple questions with the same set of multiple choice answers. Here's how I've set it up: options: string[] = ['Excellent', 'Fair', 'Good', 'Poor']; q ...

Enhancing IntelliSense to recognize exports specified in package.json

I have a package.json file where I define various scripts to be exported using the exports field. "exports": { ".": { "default": "./dist/main.es.js", "require": "./dist/main.cjs.js", ...

When emitting an event multiple times in Angular, an error may occur where properties of undefined are unable to be read, particularly in relation to the "

I am encountering an issue with my event binding on a button, specifically (click)="onStart()". The problem arises when the event this.numEmitter is emitted for the first time in setInterval, after which I receive the error message ERROR TypeError: Cannot ...

Dealing with name conflicts in Typescript when using multiple interface inheritance

Is it possible to securely implement two interfaces in Typescript that both have a member of the same name? Can this be achieved? For example: interface IFace1 { name: string; } interface IFace2 { name: string; } class SomeClass implements IFace ...

Getting a product by its slug can be achieved with Next.js 14 and Sanity by utilizing the capabilities

My dilemma involves retrieving specific product details based on the current slug displayed in the browser. While I successfully retrieve all products using the following code: export async function getAllProducts() { const productData = await client.fe ...

Encountering a server issue: Server Error Element type is invalid

I encountered an error message on my localhost: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's define ...

Could the issue at hand possibly stem from the fact that the router isn't fully operational? It appears that router.query

Having trouble retrieving the parameters from the URL using router.query. I've tried various approaches but keep getting an undefined result. It seems like I'm on the right track, though. Highlighted query param in yellow... https://i.stack.img ...

Error encountered when attempting to pass i18next instance to I18nextProvider

Issue: Error message: Type 'Promise' is missing certain properties from type 'i18n': t, init, loadResources, use, and more.ts(2740) index.d.ts(344, 3): The expected type is derived from the property 'i18n' declared within ty ...