Airbnb clone, log in after registration

Join the 2022 Full-Stack Web Dev Bootcamp!


This post is part of a new series where we build a clone of Airbnb with Next.js. See the first post here.

We now repeat the same process for the registration modal, with one more step: when we register, we need to send back the cookie like we do for the login process.

In pages/api/auth/register.js we first:

import Cookies from 'cookies'

then right before the call to send a successful response:

res.end(JSON.stringify({ status: 'success', message: 'User added' }))

We add the session cookie:

const cookies = new Cookies(req, res)
cookies.set('nextbnb_session', sessionToken, {
  httpOnly: true // true by default
})

In the frontend, in components/RegistrationModal.js, we import useStoreActions from easy-peasy:

import { useStoreActions } from 'easy-peasy'

Then we define setLoggedIn and setHideModal:

const setLoggedIn = useStoreActions((actions) => actions.login.setLoggedIn)
const setHideModal = useStoreActions((actions) => actions.modals.setHideModal)

If the response is an error, we alert and we return immediately after, otherwise we set the user as logged in:

const submit = async () => {
  const response = await axios.post('/api/auth/register', {
    email,
    password,
    passwordconfirmation
  })

  if (response.data.status === 'error') {
    alert(response.data.message)
    return
  }

  setLoggedIn(true)
  setHideModal(true)
}

Try the application: you should be able to create a new user using the registration form, the UI should change to show that you are logged in.

To logout, you can delete the cookie manually using the devtools (you can later implement logout yourself), or open a new incognito browser window.

See the code on GitHub

Next part: Create the models and move data to the db

Want to become a better Web Developer? Join the 2022 Web Development Bootcamp!

⭐️⭐️⭐️ Join the 2022 Web Development Bootcamp ⭐️⭐️⭐️