What is the best way to logout and remove cookies once the jsonwebtoken has expired?

Seeking guidance on clearing a cookie after the 15-second lifetime of a JWT token. Is this task best accomplished on the server side or can it be managed on the client side? Code snippet with description provided below

Utilizing mongoose, a user model is created and a JWT token is added to it.

const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');

const userSchema = new mongoose.Schema({
  email: { type: String, required: true },
  password: { type: String, required: true },
});

userSchema.methods.generateAuthToken = function() {
  const token = jwt.sign({ _id: this._id }, process.env.JWTPRIVATEKEY, {expiresIn: "15s"})
  return token
};

const User = mongoose.model('users', userSchema);

module.exports = { User }

const router = require('express').Router();
const { User } = require('../models/User');

router.post('/', async (req, res) => {
  try {
    const user = await User.findOne({ email: req.body.email });

    const token = user.generateAuthToken();
    res.status(200).send({ data: token, message: "Logging in is successful" });
  } catch (error) {
    console.log(error);
    res.status(500).send({ message: 'Internal Server Error' })
  }
});

data: token This key is issued by JWT. Note that it represents the JWT token generated during user creation as shown in the previous code.


Following is a basic form where a request is made and a token is received in response, then stored in cookies

import { Cookies } from "react-cookie";
    
const cookies = new Cookies();
    
const handleChange = ({ currentTarget: input }) => {
  setData({ ...data, [input.name]: input.value });
};
    
const handleSubmit = async (event) => {
  event.preventDefault();
   try {
     const url = "http://localhost:8080/api/auth";
     const { data: res } = await axios.post(url, data);
     cookies.set('token', res.data);
   } catch (error) {}
       
<form onSubmit={handleSubmit}>
  <input type="email" name={"email"} value={data.email} onChange={handleChange} required placeholder={"Email"} />
  <input type="password" name={"password"} value={data.password} onChange={handleChange} required placeholder={"Password"} />
  <button type="submit">Login</button>
</form>

This link leads to the JWT token referenced above. https://i.stack.imgur.com/RZaaL.png

Answer №1

Before making any requests that require the JWT token, it is important to verify if it has expired on the client side using jwt.verify().

jwt.verify(token, 'shhhhh', function(err, decoded) {
  if (err) {
    /*
      err = {
        name: 'TokenExpiredError',
        message: 'jwt expired',
        expiredAt: 1408621000
      }
    */
  }
});

If an error occurs inside the if (err) block, steps should be taken to invalidate the user's session, such as removing the expired token from their cookies and redirecting them to the login page.

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

Utilizing NextJS to retrieve cookie data within React components

Currently, I am working with a Next.js frontend and an Express backend. For authentication, I am utilizing cookies and have set up protected routes using Next.js middleware. The next step in my project involves accessing the cookie response within React ...

The regex routes are now unable to efficiently serve static assets

Question Is it possible to use regex or the built-in URL processor in Express to properly load static files? Expected Behavior Express should match the initial route it encounters and load files as usual. Actual Behavior Error messages indicate that ...

Material UI: Issue with implementing the dark theme

I've implemented the Context API to store the theme value. The theme itself is generated using <createMuiTheme> and passed down from <Layout> to its children through <MuiThemeProvider> and <CssBaseline>. Although I can observe ...

Cors policy error encountered in Node.js application and React application

I have developed an application using Node.js and React. I am currently hosting the server side on node.kutiza.com and the client side on finanu.kutiza.com through Namecheap. However, when I try to make a request to node.kutiza.com, I encounter an error me ...

What is the proper way to incorporate the AND OR operators into an Elasticsearch query?

Attempting to craft a query that allows users to search for specific products. The query functions with one condition but fails to return results when adding another condition. In search of this SQL query : SELECT * FROM products WHERE shop = "shop" AND ...

Scraping with Node.io in Node.js is an effective way to gather

I have been experimenting with Node.js in order to extract all the titles from this website: Here is what I have tried: var nodeio = require('node.io'); var methods = { input: false, run: function() { this.getHtml('https:// ...

The compatibility issues, absence, or failure to assign property entities in NestJS Prisma

Trying to update the Postgres database with Prisma ORM in NestJS (Microservices architecture) includes allowing users to interact with invitation requests. However, encountering the error message: Argument of type 'Invitation' is not assignable t ...

Leverage the power of react-redux useSelector with the precision of TypeScript

When attempting to utilize the new useSelector hook (shown in the example below) from react-redux in TypeScript, an error is encountered indicating that the function does not exist: Module '"../../../node_modules/@types/react-redux"' has no expo ...

Utilizing Node.js to retrieve streams in conjunction with OpenAI

I am currently working on setting up a node/react setup to stream results from openai. I came across an example project that accomplishes this using next.js. While I have successfully made the API call and received the results as expected, the challenge li ...

What are the steps to deploy a React, Next.js, and Express.js application on Netlify?

I am currently in the process of deploying my application to Netlify, featuring a combination of React, Next.js, and Express.js. While there are no errors showing up in the Netlify console, unfortunately, the site is not live as expected. https://i.stack ...

Encountering error message "no such file or directory" while attempting to run lerna bootstrap

Struggling to execute the following command lerna bootstrap --hoist On a project I downloaded from GitHub. The steps are to Download Then run lerna bootstrap --hoist However, every time I try running the lerna bootstrap --hoist command, it fails with an ...

Typed NextJs navigation to a specific route

<Link href="/about"> <a>About Us</a> </Link> Is there a way to ensure type safety with NextJs links? Currently, it is challenging to restructure the Link component as it is just a string. I stumbled upon this repos ...

A grid layout in Material UI with less than 12 columns

For my grid layout, I am looking to create columns that are separate into 10 instead of the standard 12. While I have been able to find information on increasing the number of default columns online, decreasing them has proven to be a challenge. Is it not ...

An error occurs when trying to access the Constants property in the RNCSafeAreaViewConfig object because it is undefined

There was a TypeError: undefined is not an object (evaluating 'RNCSafeAreaViewConfig.Constants') <global> InitialWindowSafeAreaInsets.ts:9:38 loadModuleImplementation require.js:322:6 <global>> index.tsx:6 loadModuleImp ...

What is the best way to arrange the JSON data in React Native using the map function

I have a JSON format like this: { "name":"xyz", "age-group":"bb" } How can I resolve the issue with this JSON? Here's the code I'm currently using: const array = [{ "name":"xyz", &q ...

Ref cannot be assigned to function components. Trying to reference a ref in a function component will not work

Having trouble passing a ref in the MenuItem component while using react-beautiful-dnd. I tried creating a HOC with React.forwardRef but it didn't work. Any help in fixing this issue would be greatly appreciated. Error: https://i.stack.imgur.com/bLIN ...

Steps for dynamically loading mui icons from mui with TypeScript

Is it possible to dynamically load MUI icons based on a string parameter using the following code snippet? import Icon from "@mui/icons-material" import SvgIcon from '@mui/material/SvgIcon'; const IconComponent = (props: typeof SvgIco ...

Unable to update the numerical value in the Material-UI version 5 TextField component

When attempting to display the decimal value 1.0 in the MUI5's TextField component, I encountered an issue. While I can change its value using the icons within the TextField, inputting any value directly seems to be ineffective. Additionally, backspac ...

What is the best way to choose a specific row with Enzyme?

We have chosen Jest for doing UI Test-Driven Development on our React application. Our component rendering structure looks like this: <Div> <Row> </Row> <ROW> <Row> <ROW> <Link> <Link> ...

How can the outcome of the useQuery be integrated with the defaultValues in the useForm function?

Hey there amazing developers! I need some help with a query. When using useQuery, the imported values can be undefined which makes it tricky to apply them as defaultValues. Does anyone have a good solution for this? Maybe something like this would work. ...