Next.js secure authenticaton

Viewed 22

I am trying to make a secure authentication with next.js

I've followed this article because it shows how do to it with api route and proxy server, but I do not understand why he uses this http-proxy module

I did the same thing without it and it seems to work perfectly fine.

Here is my pages/login.js file

import { Button } from '@mui/material'
import { useState } from 'react'

export default function loginPage() {
    const [message, setMessage] = useState();
    const handleSubmit = async (event) => {
        event.preventDefault();

        const data = {
            username: event.target.username.value,
            password: event.target.password.value
        };

        const response = await fetch('/api/login', {
            headers: {
                'Content-Type': 'application/json'
            }, 
            method: 'POST',
            body: JSON.stringify(data),
        });

        setMessage(response.message);
    }
    return (
        <div className="block">
            <form onSubmit={handleSubmit}>
                {message ? <p className="message">{message}</p> : ""}
                <label htmlFor="first">Username</label>
                <input type="text" id="username" name="username" variant="outlined" required />
  
                <label htmlFor="last">Password</label>
                <input type="text" id="password" name="password" variant="outlined" required />
  
                <div>
                  <Button className="btn" type="submit" variant="outlined">Submit</Button>
                </div>
            </form>
  
        </div>
      )
}

Here is my pages/api/[...catchAll].js

    import Cookies from "cookies"

export default async function handler(req, res) {
    console.log("HERE");
    const response = await fetch("http://localhost:7000/register", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
          },
        body: JSON.stringify(req.body)
    }).then((res) => res.json());

    const cookies = new Cookies(req, res);
    cookies.set("authorization", response.token, {
        httpOnly: true,
        sameSite: "lax",
        maxAge: 100000
    });
    res.status(200).json(response)
}
  

My front-end pages/login.js sends a request to pages/api[...catchAll].js and then a request to my back-end is being made. My back-end returns

    {
        message: "success",
        token: crypto.randomBytes(48).toString('hex')
    }

and then pages/api/[...catchAll].js sets my cookies. Why in the article the person uses the httpProxy module ? Is it more secure ? Why ?

I've seen this technique in a lot of places because of secure measurements, but I do not understand why they use this proxy server.

Could someone please explain ?

0 Answers
Related