NextJs / Advanced / Login
Login
-
Steps
1. Login form and function
import { NextPage } from 'next' import { useState } from 'react' import { setCookie } from 'cookies-next' import { useRouter } from 'next/router' const SignIn: NextPage = (props) => { // set UserInfo state with inital values const [userInfo] = useState({ email: 'kminchelle', password: '0lelplR' }) const router = useRouter() const login = async () => { // do a post call to the auth endpoint const res = await fetch('https://dummyjson.com/auth/login', { method: 'post', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: userInfo.email, password: userInfo.password, }), }) // check if response was ok if (!res.ok) { return console.error(res) } // retrieve data from the response const data = await res.json() // check if we have data if (data) { setCookie('token', data?.token) // set token to the cookie router.push('/') // redirect to home page } } return ( Login
(userInfo.email = event.target.value)} required /> (userInfo.password = event.target.value)} name="psw" required />2. implement protected routes
1. create middleware.ts
2. check token in the cookie or header
3. if no token, redirect to login
4. add matcher routes for appling protection