@joystick.js/node

Login

Log in an existing user account from the server.

To log in an existing user account, the accounts.login() method can be called from anywhere on your server.

Example Usage

index.server.js

import joystick, { accounts } from '@joystick.js/node';

joystick.app({
  routes: {
    '/api/accounts/login': {
      method: 'POST',
      handler: async (req = {}, res = {}) => {
        const login = await accounts.login({
          email_address: req?.body?.email_address,
          password: req?.body?.password,
        });
        
        res.cookie('joystick_login_token', login?.token, { httpOnly: true, secure: process.env.NODE_ENV !== 'development' });
        res.cookie('joystick_login_token_expires_at', login?.token_expires_at, { httpOnly: true, secure: process.env.NODE_ENV !== 'development' });
        
        await process.databases.mongodb.collection('customer_sessions').insertOne({
          customer_id: req?.body?.customer_id,
          user_id: login?.user?._id,
          created_at: new Date().toISOString(),
        });

        res.status(200).send({ user_id: login?.user?._id });
      },
    },
  },
});

Above, we create an advanced route for a special /api/accounts/login endpoint that we can use to log in a user and do some additional work afterward (in this case, creating a hypothetical customer session).

Because we're implementing the raw server API for accounts.login(), we manually set the joystick_login_token and joystick_login_token_expires_at cookies. Without this, a session would be created in the database but not in the browser, so for the user, it would appear they didn’t log in.

API

Definition

accounts.login(options: object) => Promise

Parameters

options object required
An object defining the parameters for the existing user account. Note: either email_address or username is required.
email_address string
The email address for the existing user account.
username string
The username for the existing user account.
password string required
The password for the existing user account.