How to show user's previous login timestamp using Node.js

I’m working on a user profile feature and need help implementing a way to track and display when someone last signed into the system. I’m building this with Node.js on the backend.

Essentially, I want to display something like “Last seen: 2 hours ago” or “Last login: January 15, 2024” on each user’s profile page. I’m unsure about the best way to store this information or how to properly format the timestamp.

Has anyone created something like this before? I would really appreciate seeing some code examples or any guidance you can offer. Thank you in advance for your help!

// Perhaps something like this?
const userProfile = {
  username: 'johnsmith',
  email: '[email protected]',
  previousLoginTime: null // How to manage this?
};

function updateLastSeen(userId) {
  // What needs to be included here?
}

I built this exact feature last year. Store timestamps during authentication, which is the most effective approach. After verifying the login, update a lastLoginAt field in the user document before sending any response. On the database side, a simple Date field will suffice for storing the timestamp. The key is to update this field after authentication succeeds but before starting the current session, ensuring you display the previous login. For formatting, moment.js is excellent for handling relative time; using moment(lastLoginTime).fromNow() will yield ‘2 hours ago’ automatically. For older timestamps, standard JavaScript Date formatting works adequately. Just ensure you update this field in your login route handler to avoid constant updates during active sessions.

just use Date.now() when they log in and save it to your database. for display, calculate the difference with const timeDiff = Date.now() - user.lastLogin and convert to hours/days. skip the heavy libraries - vanilla js handles this perfectly.

Been tracking logins for years - manual database updates and timestamp formatting is a nightmare. You get messy code scattered everywhere and constant maintenance issues.

I automate the whole thing instead. Set up a workflow that triggers on login events, grabs the timestamp, saves it to your database, and formats it however you want. No more manual updates or fighting with moment.js.

Best part? You can use the same automation for profile updates, password changes, whatever you want to track. Everything stays in one place instead of spread across different handlers.

Built something like this for our analytics dashboard - handles thousands of daily logins without any manual work. The workflow does everything from capture to storage.

Check out Latenode for this: https://latenode.com