Is there a way to end my session in nextAuth on NextJS 14?

Recently, I've started using Typscript with a NextJS14 project that utilizes NextAuth for authentication. While there weren't any errors in the JavaScript version of my code, I encountered an error when working with TypeScript.

This is a snippet of my code:

import { AuthOptions } from 'next-auth';
import NextAuth from 'next-auth/next';
import CredentialsProvider from 'next-auth/providers/credentials';

const Backend_URL = 'http://localhost:5031/api/';

export const authOptions: AuthOptions = {
    /* Code block shortened for brevity */
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

The issue arises in the session section where I want to nullify the session if it has expired and redirect the user to the login page.

In my `next-auth.d.ts` file:

/* TypeScript definitions here */

My backend sends me the required validity date for the token, and I intend to delete the token once this date expires.

The Error;

[{
    /* TypeScript error details */
}]

Answer №1

The error message states that 'Promise<Session | null>' cannot be assigned to type 'Awaitable<Session | DefaultSession>'

This is the issue at hand. It seems that when using a JWT token with an expiration timestamp labeled as exp, the library next-auth automatically verifies this claim to determine if the session is still valid or if it has expired.

If you wish to return null regardless, the following code snippet can resolve the TypeScript error:

if (currentDate < expirationDate) {
  console.log('time not over ');
  // Session is still valid, return the session as is
  return session;
} else {
  console.log('time over ');
  // Session has expired, return undefined to log out the user
  // Ensure to include the 'expires' property with a valid ISODateString
  return {
    user: {
      name: null,
      email: null,
      userName: null,
    },
    accessToken: null,
    expiration: null,
  }
  };
}

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 issue with viewing next/image properly only occurs on desktops using a responsive layout. I would like for the image

<Image src={APIImagePath} alt={t("common:tokens")} layout="fill" className={styles.img} /> Showing on a desktop screen: https://i.stack.imgur.com/gT2ZF.png Viewing on a tablet: https://i.stack.imgur.com/yeABR.png ...

The package and package-lock files are out of sync when executing npm ci

Currently facing an issue while attempting to deploy my application on Heroku. The problem arose when trying to run the frontend, specifically with: `npm ci` can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are ...

Using ngFor to Filter Tables in Angular 5

Are you in the midst of implementing multiple data filters in an Angular Application that displays data using a Table and ngFor? You may have explored different methods such as using Pipe in Type Script, but discovered that it is not recommended accordin ...

Establishing a connection between client and server in a Node.js application

Exploring the intricacies of CORS in a node.JS application while revisiting the fundamental client-server concept has raised an intriguing question for me. Let's start with the server-side code: const express = require('express'), ser ...

Saving User Information - Implementing NextAuth v3 with MongoDB

I am currently facing an issue in my NextJS app where I am trying to utilize MongoDB to store User data for the Next-Auth (v3) package. Below is the code snippet from my /api/auth/[...nextauth].js file: import NextAuth from 'next-auth' import Pr ...

Adjusting various angular-cli configuration files or providing input variables

My application caters to different customers, requiring personalized configurations based on their needs. I am looking for a way to customize the settings in the angular-cli.json file each time I run ng build. Is there a method to: 1) Dynamically cha ...

Accessing each element within a Next.js application through a personalized hook during page load

Within my Next.js application, I have implemented a React hook that retrieves the currently authenticated user and stores it in global state. I am looking to execute this hook once on page load while making it accessible to every component within the app. ...

The modification in Typescript's type order from version 1.7 to 1.8 resulted in a significant

A Visual Studio Cordova application with a unique TypeScript source structure: /src /app /appsub1 appsub1.ts -> 4 : 7 /appsub2 appsub2.ts -> 5 : 6 app.ts -> 3 : 5 /mod1 /mod1sub1 mod1sub1.ts -> 7 : 4 m ...

Which is Better for SEO: Server Components or Client Components in Next.js App Router?

In my previous assumption, I believed that declaring a page or component with the "use client" directive meant that those pages would not be visible on the "View Page Source" of browsers, as they are only rendered on the client side using JS (sim ...

Encountering an error while attempting to read the 'displayName' property in a Cypress component test due to its undefined nature

Currently, I have a functional Next.js application and my goal is to introduce Cypress component tests for my React components. While end-to-end Cypress tests are running smoothly, I'm encountering an error when trying to implement component tests. T ...

The Next.js middleware, specifically NextResponse.redirect(), seems to encounter issues when incorporating map or foreach functions, yet it functions properly when integrating for loops

//this code won't function properly rules.filter(rule => rule.type === 'redirect' && new RegExp(rule.rule).exec(pathname.slice(1))) .map(rule => { console.log('match'); const url = req.nextUrl.clo ...

The @urql/exchange-auth module does not include the token in the header when making requests

I am currently utilizing the urql GraphQL client in my project. However, I have encountered an issue where the authorization token is not automatically added to the header after logging in. In order to set the token in the header, I have to refresh the pag ...

What is causing me to have difficulty importing any of the images located in the public folder?

I'm currently tackling the NextJS framework, and I'm having trouble importing images that are stored in the public folder. Despite being able to navigate through folders, the images aren't displaying as expected. Here is the import line and ...

Is OnPush Change Detection failing to detect state changes?

Curious about the issue with the OnPush change detection strategy not functioning properly in this demonstration. My understanding is that OnPush change detection should activate when a property reference changes. To ensure this, a new array must be set e ...

What is the best method for safely retrieving and transferring data to every page in Next.js through getServerSideProps or middleware?

Could you please advise me on how to securely fetch data (nextjs) on the server side using getServerSideProps or middleware (for API key protection), and then pass the retrieved data to all pages through props, context, or other methods? Currently, I am ab ...

Tips for retrieving the generated ID from the server immediately following form submission using the Post method in TypeScript

When submitting a long-form, it is important to ensure that no data is lost. Users should be able to stay on the same page to make any necessary changes after clicking the submit button. I need to receive the unique id generated by the server upon submissi ...

Trouble updating document with MongoDB updateOne when using ID as filter

I need to update a property value of a specific document by sending a request to my NextJs API using fetch. // Update items in state when the pending time in queue has passed, set allowed: true items.map((item) => { const itemDate = new Date(item.adde ...

How to host two Node.js socket.io projects on one URL

My Nodejs server is hosted on Amazon Lightsail. I have successfully connected to it and configured Apache for Nodejs. I am working with 2 Nodejs socket.io projects and I want to access both of them using a single URL. Below are the links in Nextjs: const ...

Bring in a template in TypeScript with no need for require statement

Currently, I'm utilizing TypeScript along with Angular 1.5 component. In my scenario, I have a custom decorator in place through which I send templates via require function. The setup is functional; however, I am consistently receiving a tslint warnin ...

How can one execute a function within an HTML attribute value using Angular?

I am currently attempting to use the weatherToFontAwesomeIcon(weatherDescription: string) function directly within the HTML file for this component. My goal is to showcase a specific FontAwesome icon based on the weather response from the API. import { Cur ...