Authentication using Fetch and react-hook-form

Ankita Singh
3 min readJun 5, 2020

--

Mostly every web application has to through the authentication process, which majorly involves verifying the credentials of the user login in to your application.

As part of this project you will be able to set up your front end to hit the authentication API and fetch the jwt token. We are using then decoding the token to extract the headers information we need.

We are using react-hook-form which makes our value ( username and password ) available for auth endpoint.

Get Values and use them on submit

import { useForm } from "react-hook-form";const { register, handleSubmit } = useForm<Credentials>();

We can expose the TextField value using register in the innerRef prop of the text field. The name field has to be unique in the file.

<TextField name="email" inputRef={register} </TextField>

We can use the handleSubmit method of useForm for action of submit on form.

import { useForm } from "react-hook-form";<form onSubmit={handleSubmit(onSignIn)}>

Fetching authentication api and decoding the token

We are fetching the authenticationApi sending a POST method with the body containing the credentials of the user.

import jwtDecode from "jwt-decode";const onSignIn = async ({ email, password }: Credentials) => {    const result = await fetch("/authenticationApi", {      method: "POST",      headers: {        "Content-Type": "application/json",      },      body: JSON.stringify({        username: email,        password,       }),     });    if (result.ok) {       const promiseData = await result.json();       const { jwtToken } = promiseData;       const { "header": decoded } = jwtDecode<Token>(         jwtToken,       );       console.log("Decoded Value of the token" + decoded);     } else {       console.log("Access is not allowed");    } };

The result from the endpoint is decoded using jwtDecode library.

To allow the auth url to access the correct host which is different from the endpoint your project is running it, we need to create proxy middleware and set target host.

const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = app => {
const proxy = createProxyMiddleware("/authenticationApi", { changeOrigin: true, autoRewrite: true, target: "http://localhost:portnumber", }); app.use(proxy);};

Conclusion

In this post, I have explained and made a small demo to show how we can use the value from react-hook-form and use those credentials to authenticate the api, receive the jwt token and decode the same for extracting headers to be used in the application for further processes.

I am using context api to save the user information. You can read about it here : The power of Context API

The github project can be viewed here : https://github.com/LoginProject

--

--

Ankita Singh
Ankita Singh

No responses yet