Log In

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

/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).

Of note, because we're implementing the raw server API for accounts.login(), we need to manually set the joystick_login_token and joystick_login_token_expires_at cookies in order for the login to actually succeed (without this, a session is created in the database but not in the browser so for the user, it doesn't look like they logged in).

API Reference

accounts.login()

Function API

accounts.login(options: object) => Promise;

Arguments

  • options object

    An object defining the parameters for the existing user account. Note: either email_address or username is required.

    • email_address string

      A string defining the email address for the existing user account.

    • username string

      A string defining the username for the existing user account.

    • password string Required

      A string defining the password for the existing user account.

On This Page