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.
The code for this lesson is available at https://github.com/flaviocopes/airbnb-clone-react-nextjs-2020/tree/5-7