<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Prabhashi Meddegoda on Medium]]></title>
        <description><![CDATA[Stories by Prabhashi Meddegoda on Medium]]></description>
        <link>https://medium.com/@prabhashi.mm?source=rss-58edc42004f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7ygvwiCKMSQ8r5EHtlT1pw@2x.jpeg</url>
            <title>Stories by Prabhashi Meddegoda on Medium</title>
            <link>https://medium.com/@prabhashi.mm?source=rss-58edc42004f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:55:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prabhashi.mm/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Handle Authorization in React + Express (TypeScript) Application Using Role Based Access Control]]></title>
            <link>https://blog.stackademic.com/handle-authorization-in-react-express-typescript-application-using-role-based-access-control-2d3ab0c1dd38?source=rss-58edc42004f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d3ab0c1dd38</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[role-based-access-control]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[jwt-token]]></category>
            <dc:creator><![CDATA[Prabhashi Meddegoda]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 09:15:19 GMT</pubDate>
            <atom:updated>2023-09-20T10:44:07.972Z</atom:updated>
            <content:encoded><![CDATA[<p>We can use <strong>Role Based Access Control (RBAC)</strong> when we need to <strong>restrict</strong> the users from accessing pages / backend APIs, based on their <strong>role</strong> (permission level). For this tutorial, you need to have an application which already handles user authentication using <strong>token-based authentication</strong>. This way, we’ll have a <strong>JWT token</strong> we can use to include and retrieve user roles.</p><p>If you don’t have an application to continue this tutorial, you can view my previous articles and create an application which uses <strong>React</strong>, <strong>TypeScript</strong>, <strong>Redux Toolkit</strong>, <strong>React Router V6</strong> for the <a href="https://medium.com/@prabhashi.mm/manage-your-react-typescript-application-state-using-redux-toolkit-926d3b4abaa7">frontend</a>, and <strong>Express</strong>, <strong>TypeScript</strong>, <strong>MongoDB</strong> for <a href="https://medium.com/@prabhashi.mm/create-a-backend-application-using-express-typescript-and-handle-authentication-1f67be81da60">backend and databases</a>.</p><p>For this tutorial, we’ll have 4 roles; <em>Admin</em>, <em>Lead</em>, <em>Project Manager</em> and <em>User</em>.</p><h3>1. Authorization for Express backend</h3><p>Create a <strong>constants.ts</strong> file under the <strong>src</strong> folder in your backend application and include below.</p><pre>export enum Roles {<br>  Admin = &quot;ADMIN&quot;,<br>  Lead = &quot;LEAD&quot;,<br>  ProjectManager = &quot;PROJECT_MANAGER&quot;,<br>  User = &quot;USER&quot;,<br>}</pre><p>Then we’ll update the <strong>User model</strong> with our new field; <strong>roles</strong> which will be an <strong>array</strong> in case a user has <strong>multiple</strong> roles. We’ll add the <strong>default role</strong> as <strong>USER</strong>, so that when a user <strong>registers</strong>, he’ll be assigned with <strong>USER</strong> role by default. (If the user role needs to be updated, that has to be done by an admin from a separate Settings page.) The <strong>User.ts</strong> file will be as below.</p><pre>import mongoose, { Document, Schema } from &quot;mongoose&quot;;<br>import bcrypt from &quot;bcryptjs&quot;;<br>import { Roles } from &quot;../constants&quot;;<br><br>export interface IUser extends Document {<br>  name: string;<br>  email: string;<br>  password: string;<br>  roles: string[];<br>  comparePassword: (enteredPassword: string) =&gt; boolean;<br>}<br><br>const userSchema = new Schema&lt;IUser&gt;({<br>  name: {<br>    type: String,<br>    required: true,<br>  },<br>  email: {<br>    type: String,<br>    required: true,<br>    unique: true,<br>  },<br>  password: {<br>    type: String,<br>    required: true,<br>  },<br>  roles: {<br>    type: [String],<br>    required: true,<br>    default: [Roles.User],<br>  },<br>});<br><br>userSchema.pre(&quot;save&quot;, async function (next) {<br>  if (!this.isModified(&quot;password&quot;)) {<br>    next();<br>  }<br><br>  const salt = await bcrypt.genSalt(10);<br>  this.password = await bcrypt.hash(this.password, salt);<br>});<br><br>userSchema.methods.comparePassword = async function (enteredPassword: string) {<br>  return await bcrypt.compare(enteredPassword, this.password);<br>};<br><br>const User = mongoose.model(&quot;User&quot;, userSchema);<br><br>export default User;</pre><p>In the last tutorial, we defined the <strong>Request</strong> interface to include <strong>user</strong> information as well, let’s include <strong>roles</strong> to the list. Update the interface as below in the <strong>index.ts</strong> file.</p><pre>interface UserBasicInfo {<br>  _id: string;<br>  email: string;<br>  roles: string[];<br>}<br><br>declare global {<br>  namespace Express {<br>    interface Request {<br>      user?: UserBasicInfo | null;<br>    }<br>  }<br>}</pre><p>Currently, when a user tries to register / login, the user is created / user credentials are validated, and once it’s successful, we <strong>generate a JWT token</strong> and <strong>sends user data in the response body</strong>.</p><p>For the <strong>JWT token payload</strong>, we need to include user <strong>roles</strong> as well. Then, when a user sends a request to access a <strong>restricted</strong> resource, we can <strong>decode the token</strong> and retrieve the user roles and then decide whether we allow them to access / not.</p><p>For the <strong>response body</strong> we send back in login / register, we can include the user <strong>roles</strong> as well, so that we can restrict the page access or actions in the <strong>frontend application</strong> based on that.</p><p>Let’s update the <strong>userController.ts</strong> file as below.</p><pre>import { Request, Response } from &quot;express&quot;;<br>import User from &quot;../models/User&quot;;<br>import { generateToken, clearToken } from &quot;../utils/auth&quot;;<br>import {<br>  BadRequestError,<br>  AuthenticationError,<br>} from &quot;../middleware/errorMiddleware&quot;;<br>import asyncHandler from &quot;express-async-handler&quot;;<br><br>const registerUser = asyncHandler(async (req: Request, res: Response) =&gt; {<br>  const { name, email, password } = req.body;<br>  const userExists = await User.findOne({ email });<br><br>  if (userExists) {<br>    res.status(409).json({ message: &quot;The email already exists&quot; });<br>  }<br><br>  const user = await User.create({<br>    name,<br>    email,<br>    password,<br>  });<br><br>  if (user) {<br>    generateToken(res, {<br>      userId: user._id,<br>      userEmail: user.email,<br>      roles: user.roles,<br>    });<br>    res.status(201).json({<br>      id: user._id,<br>      name: user.name,<br>      email: user.email,<br>      roles: user.roles,<br>    });<br>  } else {<br>    throw new BadRequestError(&quot;An error occurred in registering the user&quot;);<br>  }<br>});<br><br>const authenticateUser = asyncHandler(async (req: Request, res: Response) =&gt; {<br>  const { email, password } = req.body;<br>  const user = await User.findOne({ email });<br><br>  if (user &amp;&amp; (await user.comparePassword(password))) {<br>    generateToken(res, {<br>      userId: user._id,<br>      userEmail: user.email,<br>      roles: user.roles,<br>    });<br>    res.status(201).json({<br>      id: user._id,<br>      name: user.name,<br>      email: user.email,<br>      roles: user.roles,<br>    });<br>  } else {<br>    throw new AuthenticationError(&quot;User not found / password incorrect&quot;);<br>  }<br>});<br><br>const logoutUser = asyncHandler(async (req: Request, res: Response) =&gt; {<br>  clearToken(res);<br>  res.status(200).json({ message: &quot;Successfully logged out&quot; });<br>});<br><br>export { registerUser, authenticateUser, logoutUser };</pre><p>Our <strong>generateToken()</strong> function also needs to be updated to include the new <strong>payload</strong> we’re sending.</p><pre>import jwt from &quot;jsonwebtoken&quot;;<br>import { Response } from &quot;express&quot;;<br><br>interface TokenPayload {<br>  userId: string;<br>  userEmail: string;<br>  roles: string[];<br>}<br><br>const generateToken = (res: Response, payload: TokenPayload) =&gt; {<br>  const jwtSecret = process.env.JWT_SECRET || &quot;&quot;;<br>  const token = jwt.sign(payload, jwtSecret, {<br>    expiresIn: &quot;1h&quot;,<br>  });<br><br>  res.cookie(&quot;jwt&quot;, token, {<br>    httpOnly: true,<br>    secure: process.env.NODE_ENV !== &quot;development&quot;,<br>    sameSite: &quot;strict&quot;,<br>    maxAge: 60 * 60 * 1000,<br>  });<br>};<br><br>const clearToken = (res: Response) =&gt; {<br>  res.cookie(&quot;jwt&quot;, &quot;&quot;, {<br>    httpOnly: true,<br>    expires: new Date(0),<br>  });<br>};<br><br>export { generateToken, clearToken };</pre><p>When a user tries to access a <strong>restricted</strong> resource (<em>users/:id</em> to view profile information), we already use a <strong>middleware</strong> to verify <strong>user authentication</strong>. In this middleware, we attach user info to the <strong>request</strong> object, so that we can access them in controllers/ other middleware. I was retriving the user data from database, let’s use the data we <strong>decode from the token</strong> instead.</p><pre>const authenticate = (req: Request, res: Response, next: NextFunction) =&gt; {<br>  try {<br>    let token = req.cookies.jwt;<br><br>    if (!token) {<br>      throw new AuthenticationError(&quot;Token not found&quot;);<br>    }<br><br>    const jwtSecret = process.env.JWT_SECRET || &quot;&quot;;<br>    const decoded = jwt.verify(token, jwtSecret) as JwtPayload;<br><br>    if (!decoded || !decoded.userId || !decoded.userEmail) {<br>      throw new AuthenticationError(&quot;User not found&quot;);<br>    }<br><br>    const { userId, userEmail, roles } = decoded;<br><br>    req.user = { _id: userId, email: userEmail, roles };<br>    next();<br>  } catch (e) {<br>    throw new AuthenticationError(&quot;Invalid token&quot;);<br>  }<br>};</pre><p>Now we need a <strong>middleware</strong> to <strong>authorize</strong> the user, to check if he can access the resource. Now, different routes have different access levels, <strong>eg:</strong> some should only be accessible for Admin roles, where in other cases, either Admin or User roles can access the routes. Therefore we can write a common middleware as below.</p><pre>const authorize = (allowedRoles: string[]) =&gt; {<br>  return (req: Request, res: Response, next: NextFunction) =&gt; {<br>    const userRoles = req.user?.roles;<br><br>    if (<br>      !userRoles ||<br>      !userRoles.some((role: string) =&gt; allowedRoles.includes(role))<br>    ) {<br>      return res.status(403).json({ message: &quot;Access denied&quot; });<br>    }<br><br>    next();<br>  };<br>};</pre><p>If there are no user roles <strong>or</strong> if the user roles doesn’t have any of the allowed roles, we’ll return a <strong>403</strong>.</p><p>In order to demonstrate our feature, let’s create another route as <strong><em>/users</em></strong> where we’re retrieving a list of all the users. It should only be accessible by the <strong>Admin</strong>. Update the <strong>userController.ts</strong> file as below.</p><pre>import { Request, Response } from &quot;express&quot;;<br>import User from &quot;../models/User&quot;;<br>import { BadRequestError } from &quot;../middleware/errorMiddleware&quot;;<br>import asyncHandler from &quot;express-async-handler&quot;;<br><br>const getUser = asyncHandler(async (req: Request, res: Response) =&gt; {<br>  const userId = req.user?._id;<br>  const user = await User.findById(userId, &quot;name email&quot;);<br><br>  if (!user) {<br>    throw new BadRequestError(&quot;User not available&quot;);<br>  }<br><br>  res.status(200).json(user);<br>});<br><br>const getUsers = asyncHandler(async (req: Request, res: Response) =&gt; {<br>  const users = await User.find({}, &quot;name email&quot;);<br><br>  res.status(200).json(<br>    users.map((user) =&gt; {<br>      return { id: user._id, name: user.name, email: user.email };<br>    })<br>  );<br>});<br><br>export { getUser, getUsers };</pre><p>Now we can update our routes to use the <strong>authorize</strong> middleware we created. Update the <strong>userRouter.ts</strong> as below.</p><pre>import express from &quot;express&quot;;<br>import { getUser, getUsers } from &quot;../controllers/userController&quot;;<br>import { authorize } from &quot;../middleware/authMiddleware&quot;;<br>import { Roles } from &quot;../constants&quot;;<br><br>const router = express.Router();<br><br>router.get(<br>  &quot;/:id&quot;,<br>  authorize([Roles.User, Roles.ProjectManager, Roles.Lead, Roles.Admin]),<br>  getUser<br>);<br><br>router.get(&quot;/&quot;, authorize([Roles.Admin]), getUsers);<br><br>export default router;</pre><p>That’s it for the backend. Let’s move to frontend.</p><h3>2. Authorization for React application</h3><p>We’ll update our frontend routes / page access based on the user roles. Note that <strong>frontend restriction “only” is not enough</strong>, we <strong>must</strong> protect our routes from the <strong>backend</strong> as above.</p><p>We’re using <strong>Redux Toolkit</strong> to manage our app state. Let’s update our <strong>authSlice.ts</strong> <strong>UserBasicInfo type </strong>(the info we use to validate user) to save the <strong>roles</strong> we now receive from the backend.</p><pre>type UserBasicInfo = {<br>  id: string;<br>  name: string;<br>  email: string;<br>  roles: string[];<br>};</pre><p>Let’s include the list of <strong>Roles</strong> to the <strong>constants.ts</strong> file. I have included <strong>ErrorResponse</strong> type as well to the file, since we use it everywhere.</p><pre>export type ErrorResponse = {<br>  message: string;<br>};<br><br>export enum Roles {<br>  Admin = &quot;ADMIN&quot;,<br>  Lead = &quot;LEAD&quot;,<br>  ProjectManager = &quot;PROJECT_MANAGER&quot;,<br>  User = &quot;USER&quot;,<br>}</pre><p>Since I need to demonstrate the feature we’re implementing, I’ll create another page as <strong>UserSettings.tsx</strong>, where only <strong>Admins</strong> should have access to. We’re retrieving the list of all users and show them in the page. First, let’s create the <strong>userSlice.ts</strong> to handle the state.</p><pre>import { PayloadAction, createAsyncThunk, createSlice } from &quot;@reduxjs/toolkit&quot;;<br>import axiosInstance from &quot;../api/axiosInstance&quot;;<br>import { AxiosError } from &quot;axios&quot;;<br>import { ErrorResponse } from &quot;../constants&quot;;<br><br>type UserInfo = {<br>  id: string;<br>  name: string;<br>  email: string;<br>  roles: string[];<br>};<br><br>type UserApiState = {<br>  users: UserInfo[];<br>  status: &quot;idle&quot; | &quot;loading&quot; | &quot;failed&quot;;<br>  error: string | null;<br>};<br><br>const initialState: UserApiState = {<br>  users: [],<br>  status: &quot;idle&quot;,<br>  error: null,<br>};<br><br>export const getUsers = createAsyncThunk(<br>  &quot;users/getAll&quot;,<br>  async (_, { rejectWithValue }) =&gt; {<br>    try {<br>      const response = await axiosInstance.get(&quot;/users&quot;);<br>      return response.data;<br>    } catch (error) {<br>      if (error instanceof AxiosError &amp;&amp; error.response) {<br>        const errorResponse = error.response.data;<br><br>        return rejectWithValue(errorResponse);<br>      }<br><br>      throw error;<br>    }<br>  }<br>);<br><br>const userSlice = createSlice({<br>  name: &quot;user&quot;,<br>  initialState,<br>  reducers: {},<br>  extraReducers: (builder) =&gt; {<br>    builder<br>      .addCase(getUsers.pending, (state) =&gt; {<br>        state.status = &quot;loading&quot;;<br>        state.error = null;<br>      })<br>      .addCase(<br>        getUsers.fulfilled,<br>        (state, action: PayloadAction&lt;UserInfo[]&gt;) =&gt; {<br>          state.status = &quot;idle&quot;;<br>          state.users = action.payload;<br>        }<br>      )<br>      .addCase(getUsers.rejected, (state, action) =&gt; {<br>        state.status = &quot;failed&quot;;<br>        if (action.payload) {<br>          state.error =<br>            (action.payload as ErrorResponse).message ||<br>            &quot;Retrieving users failed&quot;;<br>        } else {<br>          state.error = action.error.message || &quot;Retrieving users failed&quot;;<br>        }<br>      });<br>  },<br>});<br><br>export default userSlice.reducer;</pre><p>Add the slice reducer to the <strong>store.ts</strong> file.</p><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;<br>import authReducer from &quot;./slices/authSlice&quot;;<br>import userReducer from &quot;./slices/userSlice&quot;;<br>import notificationReducer from &quot;./slices/notificationSlice&quot;;<br>import { axiosMiddleware } from &quot;./api/middleware&quot;;<br><br>const store = configureStore({<br>  reducer: {<br>    auth: authReducer,<br>    users: userReducer,<br>    notification: notificationReducer,<br>  },<br>  middleware: (getDefaultMiddleware) =&gt;<br>    getDefaultMiddleware().concat(axiosMiddleware),<br>});<br><br>export type RootState = ReturnType&lt;typeof store.getState&gt;;<br>export type AppDispatch = typeof store.dispatch;<br><br>export default store;</pre><p>Under the <strong>pages</strong> folder, create following files.</p><p><strong>UserSettings.tsx</strong> as a Admin-only access page</p><pre>import React, { useEffect } from &quot;react&quot;;<br>import { useAppDispatch, useAppSelector } from &quot;../hooks/redux-hooks&quot;;<br>import { getUsers } from &quot;../slices/userSlice&quot;;<br><br>const UserSettings = () =&gt; {<br>  const dispatch = useAppDispatch();<br>  const users = useAppSelector((state) =&gt; state.users.users);<br><br>  useEffect(() =&gt; {<br>    dispatch(getUsers());<br>  }, []);<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;User Settings&lt;/h1&gt;<br>      {users.map((user) =&gt; (<br>        &lt;div&gt;<br>          &lt;h4&gt;User Email: &lt;/h4&gt;<br>          {user.name}<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/&gt;<br>  );<br>};<br><br>export default UserSettings;</pre><p><strong>AccessDenied.tsx</strong> file to render if the user tries to access a page he doesn’t have access to.</p><pre>import React from &quot;react&quot;;<br><br>const AccessDenied = () =&gt; {<br>  return &lt;div&gt;Access Denied&lt;/div&gt;;<br>};<br><br>export default AccessDenied;</pre><p><strong>NotFound.tsx</strong> file since we don’t have a page yet to show, in case the user tries to enter a route that <strong>doesn’t exist</strong>. (not related to authorization)</p><pre>import React from &quot;react&quot;;<br><br>const NotFound = () =&gt; {<br>  return &lt;div&gt;Not Found&lt;/div&gt;;<br>};<br><br>export default NotFound;</pre><p>Our <strong>App.tsx</strong> file is as below for the moment.</p><pre>import React from &quot;react&quot;;<br>import { Routes, Route } from &quot;react-router-dom&quot;;<br>import Home from &quot;./pages/Home&quot;;<br>import Login from &quot;./pages/Login&quot;;<br>import Register from &quot;./pages/Register&quot;;<br>import DefaultLayout from &quot;./layouts/DefaultLayout&quot;;<br>import ProtectedLayout from &quot;./layouts/ProtectedLayout&quot;;<br>import NotificationBar from &quot;./components/notification/NotificationBar&quot;;<br><br>function App() {<br>  return (<br>    &lt;&gt;<br>      &lt;NotificationBar /&gt;<br>      &lt;Routes&gt;<br>        &lt;Route element={&lt;DefaultLayout /&gt;}&gt;<br>          &lt;Route path=&quot;/login&quot; element={&lt;Login /&gt;} /&gt;<br>          &lt;Route path=&quot;/register&quot; element={&lt;Register /&gt;} /&gt;<br>        &lt;/Route&gt;<br>        &lt;Route element={&lt;ProtectedLayout /&gt;}&gt;<br>          &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;<br>        &lt;/Route&gt;<br>      &lt;/Routes&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App;</pre><p>All the <strong>protected routes </strong>should be wrapped in a route with <strong>ProtectedLayout</strong> as the layout. Therefore we can handle the access control inside the <strong>ProtectedLayout</strong> component. Update the <strong>ProtectedLayout.tsx</strong> as below.</p><pre>import React from &quot;react&quot;;<br>import { Link, Outlet } from &quot;react-router-dom&quot;;<br>import { useAppDispatch, useAppSelector } from &quot;../hooks/redux-hooks&quot;;<br>import { Navigate } from &quot;react-router-dom&quot;;<br>import AccessDenied from &quot;../pages/AccessDenied&quot;;<br><br>type ProtectedLayoutType = {<br>  allowedRoles: string[];<br>};<br><br>const ProtectedLayout = ({ allowedRoles }: ProtectedLayoutType) =&gt; {<br>  const basicUserInfo = useAppSelector((state) =&gt; state.auth.basicUserInfo);<br><br>  if (!basicUserInfo) {<br>    return &lt;Navigate replace to={&quot;/login&quot;} /&gt;;<br>  }<br><br>  if (<br>    !basicUserInfo.roles ||<br>    !basicUserInfo.roles.some((role: string) =&gt; allowedRoles.includes(role))<br>  ) {<br>    return &lt;AccessDenied /&gt;;<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;Outlet /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default ProtectedLayout;</pre><p>Now let’s update our <strong>App.tsx</strong> as below, defining <strong>allowed roles</strong> for each of the protected route.</p><pre>import React from &quot;react&quot;;<br>import { Routes, Route } from &quot;react-router-dom&quot;;<br>import Home from &quot;./pages/Home&quot;;<br>import Login from &quot;./pages/Login&quot;;<br>import Register from &quot;./pages/Register&quot;;<br>import UserSettings from &quot;./pages/UserSettings&quot;;<br>import NotFound from &quot;./pages/NotFound&quot;;<br>import DefaultLayout from &quot;./layouts/DefaultLayout&quot;;<br>import ProtectedLayout from &quot;./layouts/ProtectedLayout&quot;;<br>import NotificationBar from &quot;./components/notification/NotificationBar&quot;;<br>import { Roles } from &quot;./constants&quot;;<br><br>function App() {<br>  return (<br>    &lt;&gt;<br>      &lt;NotificationBar /&gt;<br>      &lt;Routes&gt;<br>        &lt;Route element={&lt;DefaultLayout /&gt;}&gt;<br>          &lt;Route path=&quot;/login&quot; element={&lt;Login /&gt;} /&gt;<br>          &lt;Route path=&quot;/register&quot; element={&lt;Register /&gt;} /&gt;<br>        &lt;/Route&gt;<br>        &lt;Route<br>          element={<br>            &lt;ProtectedLayout<br>              allowedRoles={[<br>                Roles.User,<br>                Roles.ProjectManager,<br>                Roles.Lead,<br>                Roles.Admin,<br>              ]}<br>            /&gt;<br>          }<br>        &gt;<br>          &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;<br>        &lt;/Route&gt;<br>        &lt;Route element={&lt;ProtectedLayout allowedRoles={[Roles.Admin]} /&gt;}&gt;<br>          &lt;Route path=&quot;/user-settings&quot; element={&lt;UserSettings /&gt;} /&gt;<br>        &lt;/Route&gt;<br>        &lt;Route path=&quot;*&quot; element={&lt;NotFound /&gt;} /&gt;<br>      &lt;/Routes&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App;</pre><p>That’s it for the access control for the frontend application.</p><p>In order to test the application, you’ll have to logout first, if you were logged in. Else, you can clear the local storage and try to login / register.</p><p>If you already have a user, login still works even though he <strong>doesn’t have any roles saved</strong> for his record in the database. This is since, <strong>Mongoose</strong> assign <strong>default</strong> value we set for the <strong>roles</strong>, if the user doesn’t have any in the database level. Therefore login should work.</p><p>If you try to <strong>register</strong> a new user, his roles will be saved to the database as [“USER”] by <strong>default</strong>.</p><p>You should be able to visit the homepage (<strong><em>“/”</em></strong>) since it’s allowed for <strong>all roles</strong>. Now, if you type <strong><em>/user-settings</em></strong> in the address bar url, you’ll only see <strong>AccessDenied</strong> page, since you don’t have <strong>ADMIN role</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*9Ag0NGBhaHJeo5470eKqvw.png" /><figcaption>Access Denied for users with no required roles</figcaption></figure><p>You can check if all the features are working by changing access levels in frontend and backend to handle different cases. You <strong>must</strong> verify that, even if a request to retrieve user list is initiated in the application, it is failed with a <strong>403 status code</strong>, if you <strong>don’t</strong> have the required roles.</p><p>Visit <a href="https://github.com/Prabashi/project-mgt-app-frontend/tree/auth-rbac">frontend codebase</a> and <a href="https://github.com/Prabashi/project-mgt-app-backend/tree/auth-rbac">backend codebase</a> to view the full implementation up to now.</p><p>Follow me and stay tuned! If you have any questions, let me know in the comments!</p><h4>Previous Steps</h4><p>Create a React application with Login / Register pages</p><p><a href="https://medium.com/@prabhashi.mm/create-a-simple-react-app-typescript-with-login-register-pages-using-create-react-app-e5c12dd6db53">Create a simple React app (TypeScript) with Login / Register pages using create-react-app</a></p><p>Manage your React application state using Redux Toolkit</p><p><a href="https://medium.com/@prabhashi.mm/manage-your-react-typescript-application-state-using-redux-toolkit-926d3b4abaa7">Manage your React (TypeScript) application state using Redux Toolkit</a></p><p>Manage notifications in your React application</p><p><a href="https://medium.com/@prabhashi.mm/handle-notifications-in-your-react-application-typescript-using-redux-toolkit-and-use-a-custom-d2e1c9de9db2">Handle notifications in your React application (TypeScript) using Redux toolkit and use a custom…</a></p><p>Create an Express backend application to handle authentication</p><p><a href="https://medium.com/@prabhashi.mm/create-a-backend-application-using-express-typescript-and-handle-authentication-1f67be81da60">Create a backend application using Express (TypeScript) and handle authentication</a></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d3ab0c1dd38" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/handle-authorization-in-react-express-typescript-application-using-role-based-access-control-2d3ab0c1dd38">Handle Authorization in React + Express (TypeScript) Application Using Role Based Access Control</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handle notifications in your React application (TypeScript) using Redux toolkit and use a custom…]]></title>
            <link>https://blog.stackademic.com/handle-notifications-in-your-react-application-typescript-using-redux-toolkit-and-use-a-custom-d2e1c9de9db2?source=rss-58edc42004f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2e1c9de9db2</guid>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[redux-middleware]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[material-ui]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Prabhashi Meddegoda]]></dc:creator>
            <pubDate>Tue, 19 Sep 2023 09:46:45 GMT</pubDate>
            <atom:updated>2023-09-20T09:34:48.542Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handle notifications in your React application (TypeScript) using Redux toolkit and use a custom Redux middleware to handle API responses</h3><p>If you’re following the <a href="https://medium.com/@prabhashi.mm/manage-your-react-typescript-application-state-using-redux-toolkit-926d3b4abaa7">series</a>, you already have a <strong>React</strong> application and a <strong>Express</strong> backend which handles <strong>authentication</strong>. But, we still haven’t implemented a method to show the users <strong>any error / success messages</strong> in the application.</p><p>Here we’re going to implement showing notifications for <strong>frontend validation errors</strong> as well as <strong>API response errors.</strong> You’ll need a frontend application which uses Redux Toolkit to handle the state, with / without APIs. Refer <a href="https://medium.com/@prabhashi.mm/create-a-simple-react-app-typescript-with-login-register-pages-using-create-react-app-e5c12dd6db53">this</a> if you need a start. Let’s start!</p><p>We’re using <strong>redux-toolkit</strong> to manage the state of the notifications; to handle if it is <strong>open</strong>, the <strong>message</strong> it shows and the <strong>type</strong> of the message. Assuming you have already setup redux, create a <strong>notificationSlice.ts</strong> under <strong>slices</strong> folder and add below code. We’re creating two <strong>reducers</strong> to handle the show / hide notifications.</p><pre>import { PayloadAction, createSlice } from &quot;@reduxjs/toolkit&quot;;<br><br>export enum NotificationType {<br>  Success = &quot;success&quot;,<br>  Error = &quot;error&quot;,<br>  Warning = &quot;warning&quot;,<br>  Info = &quot;info&quot;,<br>}<br><br>type Notification = {<br>  open: boolean;<br>  message: string;<br>  type: NotificationType;<br>};<br><br>type ShowNotification = Omit&lt;Notification, &quot;open&quot;&gt;;<br><br>const initialState = {<br>  open: false,<br>  message: &quot;&quot;,<br>  type: NotificationType.Success,<br>};<br><br>const notificationSlice = createSlice({<br>  name: &quot;notification&quot;,<br>  initialState,<br>  reducers: {<br>    showNotification: (state, action: PayloadAction&lt;ShowNotification&gt;) =&gt; {<br>      state.open = true;<br>      state.message = action.payload.message;<br>      state.type = action.payload.type;<br>    },<br>    hideNotification: (state) =&gt; {<br>      state.open = false;<br>      state.message = &quot;&quot;;<br>    },<br>  },<br>});<br><br>export const { showNotification, hideNotification } = notificationSlice.actions;<br>export default notificationSlice.reducer;</pre><p>We need to add this to the <strong>store</strong> as well.</p><pre>// Other imports here<br>import notificationReducer from &quot;./slices/notificationSlice&quot;;<br><br>const store = configureStore({<br>  reducer: {<br>    auth: authReducer,<br>    user: userReducer,<br>    notification: notificationReducer,<br>  },<br>});<br><br>// Rest of the code here</pre><p>Let’s create the notification bar component. Create a <strong>components</strong> folder under <strong>src</strong>, then a <strong>notification</strong> folder, and then <strong>NotificationBar.tsx</strong> as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*dpt9YpgGPPgk_u0lLoe2hQ.png" /><figcaption>Folder / file structure for components</figcaption></figure><p>I’m using <strong>MUI Snackbar</strong> for this and below is an updated version of one of their examples.</p><pre>import * as React from &quot;react&quot;;<br>import Stack from &quot;@mui/material/Stack&quot;;<br>import Snackbar from &quot;@mui/material/Snackbar&quot;;<br>import MuiAlert, { AlertProps } from &quot;@mui/material/Alert&quot;;<br>import { useAppSelector } from &quot;../../hooks/redux-hooks&quot;;<br>import { hideNotification } from &quot;../../slices/notificationSlice&quot;;<br>import { useAppDispatch } from &quot;../../hooks/redux-hooks&quot;;<br><br>const Alert = React.forwardRef&lt;HTMLDivElement, AlertProps&gt;(function Alert(<br>  props,<br>  ref<br>) {<br>  return &lt;MuiAlert elevation={6} ref={ref} variant=&quot;filled&quot; {...props} /&gt;;<br>});<br><br>const NotificationBar = () =&gt; {<br>  const dispatch = useAppDispatch();<br>  const { open, message, type } = useAppSelector((state) =&gt; state.notification);<br><br>  const handleClose = (<br>    event?: React.SyntheticEvent | Event,<br>    reason?: string<br>  ) =&gt; {<br>    if (reason === &quot;clickaway&quot;) {<br>      return;<br>    }<br><br>    dispatch(hideNotification());<br>  };<br><br>  return (<br>    &lt;Stack spacing={2} sx={{ width: &quot;100%&quot; }}&gt;<br>      &lt;Snackbar<br>        open={open}<br>        autoHideDuration={6000}<br>        onClose={handleClose}<br>        anchorOrigin={{ vertical: &quot;top&quot;, horizontal: &quot;center&quot; }}<br>      &gt;<br>        &lt;Alert onClose={handleClose} severity={type} sx={{ width: &quot;100%&quot; }}&gt;<br>          {message}<br>        &lt;/Alert&gt;<br>      &lt;/Snackbar&gt;<br>    &lt;/Stack&gt;<br>  );<br>};<br><br>export default NotificationBar;</pre><p>Here we retrieve <strong>open</strong>, <strong>message</strong> and <strong>type</strong> of <strong>notification state</strong> and use them in our JSX to handle the status (open / not), message and type of the notification. We also dispatch <strong>hideNotification()</strong> action in <strong>handleClose()</strong> function, so that if the user clicks on the close icon in the notification, the notification is <strong>closed</strong>. If we don’t close it, it <strong>automatically</strong> calls <strong>onClose()</strong> function after <strong>autoHideDuration</strong> (6000 milli seconds).</p><p>Since we’re showing only <strong>one notification at a time</strong>, and since we’re using this <strong>globally</strong> (in every page), we can add this component to our <strong>App.tsx</strong> file.</p><pre>// Other imports here<br>import NotificationBar from &quot;./components/notification/NotificationBar&quot;;<br><br>function App() {<br>  return (<br>    &lt;&gt;<br>      &lt;NotificationBar /&gt;<br>      &lt;Routes&gt;<br>        {/* Routes here */}<br>      &lt;/Routes&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App;</pre><p>Now let’s move into the usages of this notification bar. One usage is <strong>showing validation errors in login and register pages</strong>. Currently our Login page <strong>handleLogin()</strong> function looks like below.</p><pre>const handleLogin = async () =&gt; {<br>    // This is only a basic validation of inputs. Improve this as needed.<br>    if (email &amp;&amp; password) {<br>      try {<br>        await dispatch(<br>          login({<br>            email,<br>            password,<br>          })<br>        ).unwrap();<br>      } catch (e) {<br>        console.error(e);<br>      }<br>    } else {<br>      // Show an error message.<br>    }<br>};</pre><p>Let’s show an error notification if email / password is not provided (in <strong><em>else</em></strong> block).</p><pre>import {<br>  showNotification,<br>  NotificationType,<br>} from &quot;../slices/notificationSlice&quot;;<br><br>const handleLogin = async () =&gt; {<br>    // This is only a basic validation of inputs. Improve this as needed.<br>    if (email &amp;&amp; password) {<br>      try {<br>        await dispatch(<br>          login({<br>            email,<br>            password,<br>          })<br>        ).unwrap();<br>      } catch (e) {<br>        console.error(e);<br>      }<br>    } else {<br>      dispatch(<br>        showNotification({<br>          message: &quot;Please provide email and password&quot;,<br>          type: NotificationType.Error,<br>        })<br>      );<br>    }<br>};</pre><p>Now you can check if this works in the hosted application. You can do the same for the registration page as well.</p><pre>import {<br>  showNotification,<br>  NotificationType,<br>} from &quot;../slices/notificationSlice&quot;;<br><br>const handleRegister = async () =&gt; {<br>    // This is only a basic validation of inputs. Improve this as needed.<br>    if (name &amp;&amp; email &amp;&amp; password) {<br>      try {<br>        await dispatch(<br>          register({<br>            name,<br>            email,<br>            password,<br>          })<br>        ).unwrap();<br>      } catch (e) {<br>        console.error(e);<br>      }<br>    } else {<br>      dispatch(<br>        showNotification({<br>          message: &quot;Please fill out all the required fields&quot;,<br>          type: NotificationType.Error,<br>        })<br>      );<br>    }<br>};</pre><p>Now we can move into <strong>handling API response failures</strong>. You’ll have to refer to the <a href="https://medium.com/@prabhashi.mm/manage-your-react-typescript-application-state-using-redux-toolkit-926d3b4abaa7">previous article</a> for this part, <strong>or</strong> if you already handle API requests using Redux Toolkit features, it’ll be fine too.</p><p>Currently, we don’t do any error handling inside the <strong>thunk action creators</strong> where we initiate the requests (login, register, logout, getUser). We only set the <strong>error</strong> to our <strong>state</strong> in the <strong>extra reducers</strong> and that’s it.</p><p>But inside the <strong>components</strong> where we dispatch those actions, we call <strong>unwrap()</strong> to retrieve any errors occurred and use a <strong>try-catch block</strong> to handle it in the <strong>component level</strong>. Here, we can dispatch the <strong>showNotification</strong> action inside the catch block. This is a good approach <strong>if you need to handle errors in the component level</strong>. But when the application grows, this might be difficult to handle.</p><p>We can handle the errors in a more generalized way, where we initiate the requests. That way, we can handle the responses in a more centralized way (we don’t need to handle errors in component level). Also, I’m hoping to send <strong>meaningful error messages from the backend</strong> for known failures, therefore I need to <strong>show them as it is</strong> to the user. This is what we’re going to do here. We’ll show notifications for both success and error scenarios.</p><p>This is what our <strong>login</strong> action creator in <strong>authSlice.ts</strong> looked earlier,</p><pre>export const login = createAsyncThunk(&quot;login&quot;, async (data: User) =&gt; {<br>  const response = await axiosInstance.post(`${BACKEND_BASE_URL}/login`, data);<br>  const resData = response.data;<br><br>  localStorage.setItem(&quot;userInfo&quot;, JSON.stringify(resData));<br><br>  return resData;<br>});</pre><p>Let’s update it as follows.</p><pre>import { AxiosError } from &quot;axios&quot;;<br>import { showNotification, NotificationType } from &quot;./notificationSlice&quot;;<br>// Rest of the code here<br><br>export const login = createAsyncThunk(<br>  &quot;login&quot;,<br>  async (data: User, { rejectWithValue, dispatch }) =&gt; {<br>    try {<br>      const response = await axiosInstance.post(&quot;/login&quot;, data);<br>      const resData = response.data;<br><br>      localStorage.setItem(&quot;userInfo&quot;, JSON.stringify(resData));<br>      dispatch(<br>        showNotification({<br>          message: resData.message || &quot;Success&quot;,<br>          type: NotificationType.Success,<br>        })<br>      );<br><br>      return resData;<br>    } catch (error) {<br>      if (error instanceof AxiosError &amp;&amp; error.response) {<br>        const errorResponse = error.response.data;<br>        dispatch(<br>          showNotification({<br>            message: errorResponse.message,<br>            type: NotificationType.Error,<br>          })<br>        );<br>        return rejectWithValue(errorResponse);<br>      }<br>      dispatch(<br>        showNotification({<br>          message: &quot;An error occurred&quot;,<br>          type: NotificationType.Error,<br>        })<br>      );<br><br>      throw error;<br>    }<br>  }<br>);</pre><p>As you can see, we try the request in <strong>try block</strong>, and it it’s a success, we <strong>dispatch showNotification </strong>action to show a <strong>success</strong> message. If there’s an <strong>error</strong>, we catch it in the <strong>catch block</strong>.</p><p>When we receive a failed response, it can be either a one <strong>we handled in the backend</strong>, <strong>or</strong> it can be <strong>some other error </strong>such as a connection failure. Since we know the format of the error responses <strong>we return</strong>, we can check for them using a <strong>if block</strong> as above. If it is a error response <strong>we sent</strong>, we show the message sent from the backend. Otherwise, we show a <strong>general error</strong> (“An error occurred”).</p><p>When returning / throwing the error, <strong>if we have an error message we sent from the backend</strong>, I need to pass that to the <strong>rejected</strong> action (there’s no usecase for this for the moment). If we just <strong>throw the error </strong>received from <strong>catch block,</strong> we <strong>can’t extract</strong> those information. For that, we can use <strong>rejectWithValue()</strong> from redux-toolkit, it’s a function we can use to return an error response with a <strong>defined payload</strong>. Whatever payload we pass to this function, we can access in the <strong>payload</strong> of the <strong>rejected action</strong>. We can do something like below in <strong>login</strong> <strong>rejected</strong> case.</p><pre>// Define type at the top<br>type ErrorResponse = {<br>  message: string;<br>};<br><br>// Rest of the code here<br><br>.addCase(login.rejected, (state, action) =&gt; {<br>  state.status = &quot;failed&quot;;<br><br>  if (action.payload) {<br>    state.error = (action.payload as ErrorResponse).message || &quot;Login failed&quot;;<br>  } else {<br>    state.error = action.error.message || &quot;Login failed&quot;;<br>  }<br>})</pre><p>Now, you can do the changes we did to <strong>login()</strong> earlier, to all the other thunk action creators (register, logout, getUser). But as you can see, this results in <strong>code duplication</strong>, and when our application grows, it’ll be difficult to handle this in every case.</p><p>One of the <strong>simple</strong> solutions for this is, creating a <strong>custom middleware</strong> for the <strong>redux store</strong>. When we use this middleware, every action will call this middleware and if the conditions match, it will perform any actions we need to dispatch. Adding custom middleware causes <strong>additional overhead</strong>, but since this is a simple one, we can go ahead with this solution.</p><p>I included the middleware file inside the <strong>api</strong> folder, but it is up to you. Create a <strong>middleware.ts</strong> file and include the following.</p><pre>import { Middleware } from &quot;@reduxjs/toolkit&quot;;<br>import {<br>  showNotification,<br>  NotificationType,<br>} from &quot;../slices/notificationSlice&quot;;<br><br>export const axiosMiddleware: Middleware =<br>  ({ dispatch }) =&gt;<br>  (next) =&gt;<br>  async (action) =&gt; {<br>    if (action.type.endsWith(&quot;/rejected&quot;)) {<br>      const errorMessage = action.payload?.message || &quot;An error occurred!&quot;;<br><br>      dispatch(<br>        showNotification({<br>          type: NotificationType.Error,<br>          message: errorMessage,<br>        })<br>      );<br>    } else if (action.type.endsWith(&quot;/fulfilled&quot;)) {<br>      const successMessage = action.payload?.message || &quot;Sucess!&quot;;<br><br>      dispatch(<br>        showNotification({<br>          type: NotificationType.Success,<br>          message: successMessage,<br>        })<br>      );<br>    }<br><br>    return next(action);<br>  };</pre><p>If the <strong>action type</strong> ends with <strong><em>/rejected</em></strong>, meaning the request is <strong>failed</strong>, we retrieve the error message<strong> if any</strong>, and show error notification. If the request was successful (<strong><em>/fulfilled</em></strong>), then we show a success notification. This middleware centralizes the notification handling for the API request responses. We need to tell the <strong>store</strong> to use this <strong>middleware</strong> as below.</p><pre>import { axiosMiddleware } from &quot;./api/middleware&quot;;<br>// Rest of the imports here<br><br>const store = configureStore({<br>  reducer: {<br>    auth: authReducer,<br>    user: userReducer,<br>    notification: notificationReducer,<br>  },<br>  middleware: (getDefaultMiddleware) =&gt;<br>    getDefaultMiddleware().concat(axiosMiddleware),<br>});<br><br>// Rest of the code here</pre><p>Now, we <strong>don’t need</strong> all the handling we did in the <strong>login() </strong>action creator. But we still need to <strong>pass the payload</strong> we receive from the error response, to the middleware (note the <strong>rejectWithValue()</strong> in <strong>catch</strong> block). Update <strong>login()</strong> as below.</p><pre>export const login = createAsyncThunk(<br>  &quot;login&quot;,<br>  async (data: User, { rejectWithValue }) =&gt; {<br>    try {<br>      const response = await axiosInstance.post(&quot;/login&quot;, data);<br>      const resData = response.data;<br><br>      localStorage.setItem(&quot;userInfo&quot;, JSON.stringify(resData));<br><br>      return resData;<br>    } catch (error) {<br>      if (error instanceof AxiosError &amp;&amp; error.response) {<br>        const errorResponse = error.response.data;<br><br>        return rejectWithValue(errorResponse);<br>      }<br><br>      throw error;<br>    }<br>  }<br>);</pre><p>You can update other ones in the same manner. Below is the final code for the <strong>authSlice.ts</strong>. We don’t actually use error state we set inside the extra reducers, but I’m keep it as this for the moment.</p><pre>import { createSlice, createAsyncThunk, PayloadAction } from &quot;@reduxjs/toolkit&quot;;<br>import axiosInstance from &quot;../api/axiosInstance&quot;;<br>import { AxiosError } from &quot;axios&quot;;<br><br>type User = {<br>  email: string;<br>  password: string;<br>};<br><br>type NewUser = User &amp; {<br>  name: string;<br>};<br><br>type UserBasicInfo = {<br>  id: string;<br>  name: string;<br>  email: string;<br>};<br><br>type UserProfileData = {<br>  name: string;<br>  email: string;<br>};<br><br>type ErrorResponse = {<br>  message: string;<br>};<br><br>type AuthApiState = {<br>  basicUserInfo?: UserBasicInfo | null;<br>  userProfileData?: UserProfileData | null;<br>  status: &quot;idle&quot; | &quot;loading&quot; | &quot;failed&quot;;<br>  error: string | null;<br>};<br><br>const initialState: AuthApiState = {<br>  basicUserInfo: localStorage.getItem(&quot;userInfo&quot;)<br>    ? JSON.parse(localStorage.getItem(&quot;userInfo&quot;) as string)<br>    : null,<br>  userProfileData: undefined,<br>  status: &quot;idle&quot;,<br>  error: null,<br>};<br><br>export const login = createAsyncThunk(<br>  &quot;login&quot;,<br>  async (data: User, { rejectWithValue }) =&gt; {<br>    try {<br>      const response = await axiosInstance.post(&quot;/login&quot;, data);<br>      const resData = response.data;<br><br>      localStorage.setItem(&quot;userInfo&quot;, JSON.stringify(resData));<br><br>      return resData;<br>    } catch (error) {<br>      if (error instanceof AxiosError &amp;&amp; error.response) {<br>        const errorResponse = error.response.data;<br><br>        return rejectWithValue(errorResponse);<br>      }<br><br>      throw error;<br>    }<br>  }<br>);<br><br>export const register = createAsyncThunk(<br>  &quot;register&quot;,<br>  async (data: NewUser, { rejectWithValue }) =&gt; {<br>    try {<br>      const response = await axiosInstance.post(&quot;/register&quot;, data);<br>      const resData = response.data;<br><br>      localStorage.setItem(&quot;userInfo&quot;, JSON.stringify(resData));<br><br>      return resData;<br>    } catch (error) {<br>      if (error instanceof AxiosError &amp;&amp; error.response) {<br>        const errorResponse = error.response.data;<br><br>        return rejectWithValue(errorResponse);<br>      }<br><br>      throw error;<br>    }<br>  }<br>);<br><br>export const logout = createAsyncThunk(<br>  &quot;logout&quot;,<br>  async (_, { rejectWithValue }) =&gt; {<br>    try {<br>      const response = await axiosInstance.post(&quot;/logout&quot;, {});<br>      const resData = response.data;<br><br>      localStorage.removeItem(&quot;userInfo&quot;);<br><br>      return resData;<br>    } catch (error) {<br>      if (error instanceof AxiosError &amp;&amp; error.response) {<br>        const errorResponse = error.response.data;<br><br>        return rejectWithValue(errorResponse);<br>      }<br><br>      throw error;<br>    }<br>  }<br>);<br><br>export const getUser = createAsyncThunk(<br>  &quot;users/profile&quot;,<br>  async (userId: string, { rejectWithValue }) =&gt; {<br>    try {<br>      const response = await axiosInstance.get(`/users/${userId}`);<br>      return response.data;<br>    } catch (error) {<br>      if (error instanceof AxiosError &amp;&amp; error.response) {<br>        const errorResponse = error.response.data;<br><br>        return rejectWithValue(errorResponse);<br>      }<br><br>      throw error;<br>    }<br>  }<br>);<br><br>const authSlice = createSlice({<br>  name: &quot;auth&quot;,<br>  initialState,<br>  reducers: {},<br>  extraReducers: (builder) =&gt; {<br>    builder<br>      .addCase(login.pending, (state) =&gt; {<br>        state.status = &quot;loading&quot;;<br>        state.error = null;<br>      })<br>      .addCase(<br>        login.fulfilled,<br>        (state, action: PayloadAction&lt;UserBasicInfo&gt;) =&gt; {<br>          state.status = &quot;idle&quot;;<br>          state.basicUserInfo = action.payload;<br>        }<br>      )<br>      .addCase(login.rejected, (state, action) =&gt; {<br>        state.status = &quot;failed&quot;;<br>        if (action.payload) {<br>          state.error =<br>            (action.payload as ErrorResponse).message || &quot;Login failed&quot;;<br>        } else {<br>          state.error = action.error.message || &quot;Login failed&quot;;<br>        }<br>      })<br><br>      .addCase(register.pending, (state) =&gt; {<br>        state.status = &quot;loading&quot;;<br>        state.error = null;<br>      })<br>      .addCase(<br>        register.fulfilled,<br>        (state, action: PayloadAction&lt;UserBasicInfo&gt;) =&gt; {<br>          state.status = &quot;idle&quot;;<br>          state.basicUserInfo = action.payload;<br>        }<br>      )<br>      .addCase(register.rejected, (state, action) =&gt; {<br>        state.status = &quot;failed&quot;;<br>        if (action.payload) {<br>          state.error =<br>            (action.payload as ErrorResponse).message || &quot;Registration failed&quot;;<br>        } else {<br>          state.error = action.error.message || &quot;Registration failed&quot;;<br>        }<br>      })<br><br>      .addCase(logout.pending, (state) =&gt; {<br>        state.status = &quot;loading&quot;;<br>        state.error = null;<br>      })<br>      .addCase(logout.fulfilled, (state, action) =&gt; {<br>        state.status = &quot;idle&quot;;<br>        state.basicUserInfo = null;<br>      })<br>      .addCase(logout.rejected, (state, action) =&gt; {<br>        state.status = &quot;failed&quot;;<br>        if (action.payload) {<br>          state.error =<br>            (action.payload as ErrorResponse).message || &quot;Logout failed&quot;;<br>        } else {<br>          state.error = action.error.message || &quot;Logout failed&quot;;<br>        }<br>      })<br><br>      .addCase(getUser.pending, (state) =&gt; {<br>        state.status = &quot;loading&quot;;<br>        state.error = null;<br>      })<br>      .addCase(getUser.fulfilled, (state, action) =&gt; {<br>        state.status = &quot;idle&quot;;<br>        state.userProfileData = action.payload;<br>      })<br>      .addCase(getUser.rejected, (state, action) =&gt; {<br>        state.status = &quot;failed&quot;;<br>        if (action.payload) {<br>          state.error =<br>            (action.payload as ErrorResponse).message ||<br>            &quot;Get user profile data failed&quot;;<br>        } else {<br>          state.error = action.error.message || &quot;Get user profile data failed&quot;;<br>        }<br>      });<br>  },<br>});<br><br>export default authSlice.reducer;</pre><p>Try out different scenarios in the application UI and test if it works. I have <strong>updated my backend application </strong>a bit, in order to send <strong>user-friendly error messages</strong> and to use the custom error handler middleware we created in the backend. You can view the updated backend code <a href="https://github.com/Prabashi/project-mgt-app-backend/tree/auth">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*b-2dwCyxQmOsN5glb5XAcA.png" /><figcaption>Error message notification with message received from backend</figcaption></figure><p>Now you <strong>don’t</strong> need <strong>try-catch block</strong> or <strong>unwrap()</strong> in the <strong>component level</strong>. The updated handlers are as below for login, register and logout scenarios.</p><pre>const handleLogin = async () =&gt; {<br>    // This is only a basic validation of inputs. Improve this as needed.<br>    if (email &amp;&amp; password) {<br>      dispatch(<br>        login({<br>          email,<br>          password,<br>        })<br>      );<br>    } else {<br>      dispatch(<br>        showNotification({<br>          message: &quot;Please provide email and password&quot;,<br>          type: NotificationType.Error,<br>        })<br>      );<br>    }<br>  };</pre><pre>const handleRegister = async () =&gt; {<br>    // This is only a basic validation of inputs. Improve this as needed.<br>    if (name &amp;&amp; email &amp;&amp; password) {<br>      dispatch(<br>        register({<br>          name,<br>          email,<br>          password,<br>        })<br>      );<br>    } else {<br>      dispatch(<br>        showNotification({<br>          message: &quot;Please fill out all the required fields&quot;,<br>          type: NotificationType.Error,<br>        })<br>      );<br>    }<br>  };</pre><pre>const handleLogout = async () =&gt; {<br>    await dispatch(logout());<br>    navigate(&quot;/login&quot;);<br>  };</pre><p>You can view the full implementation for frontend application up to now <a href="https://github.com/Prabashi/project-mgt-app-frontend/tree/auth">here</a>.</p><p>Follow me and stay tuned! If you have any questions, let me know in the comments!</p><h4>Next Steps</h4><p>We’ll handle <strong>authorization</strong> for the frontend and backend applications, using <strong>Role Based Access Control</strong>.</p><h4>Previous Steps</h4><p>Create a react app with Register and Login pages</p><p><a href="https://medium.com/@prabhashi.mm/create-a-simple-react-app-typescript-with-login-register-pages-using-create-react-app-e5c12dd6db53">Create a simple React app (TypeScript) with Login / Register pages using create-react-app</a></p><p>Manage your React application state using Redux Toolkit</p><p><a href="https://medium.com/@prabhashi.mm/manage-your-react-typescript-application-state-using-redux-toolkit-926d3b4abaa7">Manage your React (TypeScript) application state using Redux Toolkit</a></p><p>Create a Express backend application to handle authentication</p><p><a href="https://medium.com/@prabhashi.mm/create-a-backend-application-using-express-typescript-and-handle-authentication-1f67be81da60">Create a backend application using Express (TypeScript) and handle authentication</a></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2e1c9de9db2" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/handle-notifications-in-your-react-application-typescript-using-redux-toolkit-and-use-a-custom-d2e1c9de9db2">Handle notifications in your React application (TypeScript) using Redux toolkit and use a custom…</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Backend Application Using Express (TypeScript) and Handle Authentication]]></title>
            <link>https://blog.stackademic.com/create-a-backend-application-using-express-typescript-and-handle-authentication-1f67be81da60?source=rss-58edc42004f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f67be81da60</guid>
            <category><![CDATA[express]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt-token]]></category>
            <dc:creator><![CDATA[Prabhashi Meddegoda]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 16:26:36 GMT</pubDate>
            <atom:updated>2023-09-20T10:43:35.263Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll create a <strong>ExpressJS</strong> backend with <strong>TypeScript</strong>, implement <strong>authentication</strong> and create a <strong>custom middleware</strong> to validate user authentication and to handle errors. We’ll use <strong>MongoDB</strong> to store our user data.</p><p>We’ll be implementing token based authentication using <strong>JWT tokens.</strong> We’ll use <strong>cookies</strong> to store the token.</p><h4>1. Creating the ExpressJS application with TypeScript</h4><p>You can follow below steps to create a simple Express backend with TypeScript.</p><p>Create a folder for the backend application and run the following commands in the terminal to initialize a NodeJS project and to install the dependencies.</p><pre>npm init -y<br>npm install express<br>npm install typescript @types/node @types/express ts-node nodemon --save-dev</pre><p>Run below command to create a <strong>tsconfig.json</strong> file.</p><pre>npx tsc --init</pre><p>Make sure the following are uncommented in the file, with the given values.</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES6&quot;,<br>    &quot;module&quot;: &quot;CommonJS&quot;,<br>    &quot;outDir&quot;: &quot;./dist&quot;,<br>    &quot;rootDir&quot;: &quot;./src&quot;,<br>    &quot;strict&quot;: true,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;skipLibCheck&quot;: true<br>  }<br>}</pre><p>Create a <strong>src</strong> folder and include <strong>index.ts</strong> file with following initial implementation.</p><pre>import express from &#39;express&#39;;<br><br>const app = express();<br>const port = process.env.PORT || 8000;<br><br>app.listen(port, () =&gt; {<br>  console.log(`Server is running on port ${port}`);<br>});</pre><p>Include the following scripts in package.json.</p><pre>&quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node dist/index.js&quot;,<br>    &quot;dev&quot;: &quot;nodemon src/index.ts&quot;,<br>    &quot;build&quot;: &quot;tsc&quot;<br>  }</pre><p>Now you can up the server locally by running below command. Since we’re using <strong>nodemon</strong> (installed previously), each time we do a change in the code and save, the server will be automatically updated.</p><pre>npm run dev</pre><p>Now you have a Express server up and running locally. Let’s add the routes and the implementations associated with the register, login and logout processes.</p><h4>2. Add authentication implementation for the backend</h4><p>Create the following folder/file structure and add the initial code as below for each file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*j5Pl6PO1hpHvKV1RF8yImQ.png" /><figcaption>Folder and file structure for backend</figcaption></figure><p>For authController.ts,</p><pre>import { Request, Response } from &quot;express&quot;;<br><br>const registerUser = (req: Request, res: Response) =&gt; {};<br><br>const authenticateUser = (req: Request, res: Response) =&gt; {};<br><br>const logoutUser = (req: Request, res: Response) =&gt; {};<br><br>export { registerUser, authenticateUser, logoutUser };</pre><p>For authRouter.ts,</p><pre>import express from &quot;express&quot;;<br>import {<br>  registerUser,<br>  authenticateUser,<br>  logoutUser,<br>} from &quot;../controllers/authController&quot;;<br><br>const router = express.Router();<br><br>router.post(&quot;/register&quot;, registerUser);<br>router.post(&quot;/login&quot;, authenticateUser);<br>router.post(&quot;/logout&quot;, logoutUser);<br><br>export default router;</pre><p>Update the <strong>index.ts</strong> file as below, importing and using authRouter.</p><pre>import express from &quot;express&quot;;<br>import authRouter from &quot;./routes/authRouter&quot;;<br><br>const app = express();<br>const port = process.env.PORT || 3000;<br><br>app.listen(port, () =&gt; {<br>  console.log(`Server is running on port ${port}`);<br>});<br><br>app.use(authRouter);</pre><p>Let’s install <strong>jsonwebtoken</strong> library to work with <strong>JWT tokens</strong>, and <strong>bcryptjs</strong> to hash the password.</p><pre>npm i bcryptjs jsonwebtoken<br>npm i -D @types/bcryptjs @types/jsonwebtoken</pre><p>We’re using <strong>mongoose</strong>, which enables us to work with <strong>MongoDB</strong> in NodeJS environment.</p><pre>npm i mongoose</pre><p>Now, let’s create User.ts model to include the properties and methods of User objects.</p><pre>import mongoose, { Document, Schema } from &quot;mongoose&quot;;<br>import bcrypt from &quot;bcryptjs&quot;;<br><br>export interface IUser extends Document {<br>  name: string;<br>  email: string;<br>  password: string;<br>  comparePassword: (enteredPassword: string) =&gt; boolean;<br>}<br><br>const userSchema = new Schema&lt;IUser&gt;({<br>  name: {<br>    type: String,<br>    required: true,<br>  },<br>  email: {<br>    type: String,<br>    required: true,<br>    unique: true,<br>  },<br>  password: {<br>    type: String,<br>    required: true,<br>  },<br>});<br><br>userSchema.pre(&quot;save&quot;, async function (next) {<br>  if (!this.isModified(&quot;password&quot;)) {<br>    next();<br>  }<br><br>  const salt = await bcrypt.genSalt(10);<br>  this.password = await bcrypt.hash(this.password, salt);<br>});<br><br>userSchema.methods.comparePassword = async function (enteredPassword: string) {<br>  return await bcrypt.compare(enteredPassword, this.password);<br>};<br><br>const User = mongoose.model(&quot;User&quot;, userSchema);<br><br>export default User;</pre><p>Let’s implement the functions we defined in the <strong>authController.ts </strong>file.</p><pre>import { Request, Response } from &quot;express&quot;;<br>import User from &quot;../models/User&quot;;<br>import { generateToken, clearToken } from &quot;../utils/auth&quot;;<br><br>const registerUser = async (req: Request, res: Response) =&gt; {<br>  const { name, email, password } = req.body;<br>  const userExists = await User.findOne({ email });<br><br>  if (userExists) {<br>    res.status(400).json({ message: &quot;The user already exists&quot; });<br>  }<br><br>  const user = await User.create({<br>    name,<br>    email,<br>    password,<br>  });<br><br>  if (user) {<br>    generateToken(res, user._id);<br>    res.status(201).json({<br>      id: user._id,<br>      name: user.name,<br>      email: user.email,<br>    });<br>  } else {<br>    res.status(400).json({ message: &quot;An error occurred in creating the user&quot; });<br>  }<br>};<br><br>const authenticateUser = async (req: Request, res: Response) =&gt; {<br>  const { email, password } = req.body;<br>  const user = await User.findOne({ email });<br><br>  if (user &amp;&amp; (await user.comparePassword(password))) {<br>    generateToken(res, user._id);<br>    res.status(201).json({<br>      id: user._id,<br>      name: user.name,<br>      email: user.email,<br>    });<br>  } else {<br>    res.status(401).json({ message: &quot;User not found / password incorrect&quot; });<br>  }<br>};<br><br>const logoutUser = (req: Request, res: Response) =&gt; {<br>  clearToken(res);<br>  res.status(200).json({ message: &quot;User logged out&quot; });<br>};<br><br>export { registerUser, authenticateUser, logoutUser };</pre><p>If the user successfully registers / logs in, we need to generate a <strong>JWT token</strong> and set it as a <strong>cookie</strong>. If the user logs out, we need to clear the cookie. We’re implementing those functionalities in auth.ts file and are using them as above.</p><p>Create a <strong>utils</strong> folder and a <strong>auth.ts</strong> file under it.</p><pre>import jwt from &quot;jsonwebtoken&quot;;<br>import { Response } from &quot;express&quot;;<br><br>const generateToken = (res: Response, userId: string) =&gt; {<br>  const jwtSecret = process.env.JWT_SECRET || &quot;&quot;;<br>  const token = jwt.sign({ userId }, jwtSecret, {<br>    expiresIn: &quot;1h&quot;,<br>  });<br><br>  res.cookie(&quot;jwt&quot;, token, {<br>    httpOnly: true,<br>    secure: process.env.NODE_ENV !== &quot;development&quot;,<br>    sameSite: &quot;strict&quot;,<br>    maxAge: 60 * 60 * 1000,<br>  });<br>};<br><br>const clearToken = (res: Response) =&gt; {<br>  res.cookie(&quot;jwt&quot;, &quot;&quot;, {<br>    httpOnly: true,<br>    expires: new Date(0),<br>  });<br>};<br><br>export { generateToken, clearToken };</pre><p>We include the <strong>userId</strong> in the token and set the expiration to 1 hour. Then we set a cookie as <strong>jwt</strong> with the generated token value. This will set the cookie in the client and for all the subsequent requests, the cookie will be sent automatically in the header.</p><p>You need to connect a <strong>Mongo database</strong> to the backend. You can create one <strong>online</strong> by visiting their <a href="https://www.mongodb.com/">site</a>. You’ll be able to obtain a <strong>url</strong> to connect to the database once you create one.</p><p>Create a <strong>connections</strong> folder and add a <strong>userDB.ts</strong> file.</p><pre>import mongoose from &quot;mongoose&quot;;<br><br>const connectUserDB = async () =&gt; {<br>  try {<br>    const conn = await mongoose.connect(process.env.MONGODB_URI || &quot;&quot;);<br>    console.log(`MongoDB Connected: ${conn.connection.host}`);<br>  } catch (error: any) {<br>    console.error(`Error: ${error.message}`);<br>    process.exit(1);<br>  }<br>};<br><br>export default connectUserDB;</pre><p>Import it in <strong>index.ts</strong> file and initialize connecting to the DB.</p><pre>import connectUserDB from &quot;./connections/userDB&quot;;<br><br>connectUserDB();</pre><p>We didn’t create our .env file yet, let’s create that. Install <strong>dotenv</strong> library, configure it in <strong>index.ts</strong> file and create a <strong>.env</strong> file in the <strong>root folder</strong>.</p><pre>npm i dotenv</pre><p>index.ts</p><pre>import dotenv from &quot;dotenv&quot;;<br><br>dotenv.config();</pre><p>Include the following in the .env file with the values of yours.</p><pre>PORT=8000<br>JWT_SECRET=abc123<br>NODE_ENV=development<br>MONGODB_URI=mongodb_url_with_username_password</pre><p>Let’s continue. In order to identify the request object as a json, we need to use a parser.</p><pre>npm i body-parser</pre><p>In index.ts file,</p><pre>import bodyParser from &quot;body-parser&quot;;<br><br>app.use(bodyParser.json());</pre><p>Now let’s restart the application. If you’re following the <a href="https://medium.com/@prabhashi.mm/create-a-simple-react-app-typescript-with-login-register-pages-using-create-react-app-e5c12dd6db53">series</a>, you can use the frontend to test if the application functionalities work. Otherwise, you can use Postman to test the APIs.</p><p>If you try registering using the application UI, your request will fail with a <strong>CORS error</strong>. The reason is, the domain we’re trying to access (localhost:8000) is different than the one we’re at (localhost:3000), and since we have not configured the server to allow this, we’re not allowed to access the resources. To fix this, install <strong>cors</strong> package and add the required configuration to <strong>index.ts</strong> file as below. We have to set <strong>credentials</strong> to true as well, since we need to allow credentials too. These configure two headers; <strong>Access-Control-Allow-Origin</strong> and <strong>Access-Control-Allow-Credentials</strong>.</p><pre>npm i cors<br>npm i -D @types/cors</pre><pre>import cors from &quot;cors&quot;;<br><br>app.use(<br>  cors({<br>    origin: &quot;http://localhost:3000&quot;,<br>    credentials: true,<br>  })<br>);</pre><p>Now your application should work!</p><h4>3. Custom middleware to validate user and to handle errors</h4><p>When the application grows, we’ll be adding more APIs to the backend. Almost all of them should only be accessible to those who are authenticated (logged in). Therefore, when an API is called, we have to first check if the <strong>token</strong> we received is a valid one. If the token validates, we continue the processing, otherwise we have to return an error.</p><p>In order to validate the token, we can implement a <strong>middleware</strong> in the backend and call it for each protected API, before processing them.</p><p>We need to access the <strong>jwt token</strong> saved in the <strong>cookies</strong> in the request, so that we can verify if it’s valid. Install <strong>cookie-parser</strong> and import it to the <strong>index.ts</strong> file. Make sure to <strong>add the cookieParser() before the routes / middlewares where the cookies are accessed</strong>.</p><pre>npm i cookie-parser<br>npm i -D @types/cookie-parser</pre><pre>import cookieParser from &quot;cookie-parser&quot;;<br><br>app.use(cookieParser());</pre><p>Create a <strong>middleware</strong> folder and include a <strong>authMiddleware.ts</strong> file. We’ll implement a function to verify the token received. If the token is valid, we can retrieve the user data and pass them to the controller (We might need user data for some of the controllers in the future). Instead of retrieving user data from the database, we can <strong>include</strong> the needed data to the <strong>JWT token</strong> we generate and <strong>decode</strong> it to retrieve the data, we’ll do that later.</p><p>We’ll be passing the <strong>user data</strong> by assigning the data to a <strong>custom field in request object</strong>. In order to do this in TypeScript, you need to update the <strong>Request interface</strong> as below. Include the below in <strong>index.ts</strong> file.</p><pre>interface UserBasicInfo {<br>  _id: string;<br>  name: string;<br>  email: string;<br>}<br><br>declare global {<br>  namespace Express {<br>    interface Request {<br>      user?: UserBasicInfo | null;<br>    }<br>  }<br>}</pre><p>Now you can assign user data to the req object in the middleware.</p><p>Install <strong>express-async-handler</strong> package. By using this <strong>asyncHandler</strong> middleware, we can handle the <strong>exceptions</strong> in async functions and pass them to the error handler (default or custom).</p><pre>npm i express-async-handler</pre><p>Update the <strong>authMiddleware.ts</strong> file as below. Try-catch block is not a must, since any exceptions are handled by the <strong>asyncHandler</strong>. But we’re going to create <strong>a custom error handler</strong> (a middleware) and I need to pass a custom error message to that error handler.</p><p>Express does have a <strong>default</strong> error handler; below code uses that handler and sends the response along with the error, once an exception occurs.</p><pre>import { Request, Response, NextFunction } from &quot;express&quot;;<br>import jwt, { JwtPayload } from &quot;jsonwebtoken&quot;;<br>import User from &quot;../models/User&quot;;<br>import asyncHandler from &quot;express-async-handler&quot;;<br><br>const authenticate = asyncHandler(<br>  async (req: Request, res: Response, next: NextFunction) =&gt; {<br>    try {<br>      let token = req.cookies.jwt;<br><br>      if (!token) {<br>        res.status(401);<br>        throw new Error(&quot;Not authorized, token not found&quot;);<br>      }<br><br>      const jwtSecret = process.env.JWT_SECRET || &quot;&quot;;<br>      const decoded = jwt.verify(token, jwtSecret) as JwtPayload;<br><br>      if (!decoded || !decoded.userId) {<br>        res.status(401);<br>        throw new Error(&quot;Not authorized, userId not found&quot;);<br>      }<br><br>      const user = await User.findById(decoded.userId, &quot;_id name email&quot;);<br><br>      if (!user) {<br>        res.status(401);<br>        throw new Error(&quot;Not authorized, user not found&quot;);<br>      }<br><br>      req.user = user;<br>      next();<br>    } catch (e) {<br>      res.status(401);<br>      throw new Error(&quot;Not authorized, invalid token&quot;);<br>    }<br>  }<br>);<br><br>export { authenticate };</pre><p>But the default error response might expose <strong>sensitive information</strong> about the server. Also, we won’t have control over the response sent when an exception occurs. Therefore it’s better to create a custom error handler and add it as a middleware.</p><p>Let’s create a <strong>errorMiddleware.ts</strong> file and include below code.</p><pre>import { NextFunction, Request, Response } from &quot;express&quot;;<br><br>const errorHandler = (<br>  err: Error,<br>  req: Request,<br>  res: Response,<br>  next: NextFunction<br>) =&gt; {<br>  console.error(err.stack);<br><br>  if (err instanceof AuthenticationError) {<br>    res.status(401).json({ message: &quot;Unauthorized: &quot; + err.message });<br>  } else {<br>    res.status(500).json({ message: &quot;Internal Server Error&quot; });<br>  }<br>};<br><br>class AuthenticationError extends Error {<br>  constructor(message: string) {<br>    super(message);<br>    this.name = &quot;AuthenticationError&quot;;<br>  }<br>}<br><br>export { errorHandler, AuthenticationError };</pre><p>Now import it and add app.use line <strong>after</strong> all the middleware and routes we added.</p><pre>import { errorHandler } from &quot;./middleware/errorMiddleware&quot;;<br><br>app.use(errorHandler);</pre><p>Now, if we throw a new error, it will be handled by errorHandler middleware. If we throw a <strong>AuthenticationError</strong> error, the response will be of <strong>401</strong> status code (unauthorized). Otherwise, it’ll be a <strong>500</strong>. We can add more custom error types such as AuthenticationError later, as the app grows.</p><p>Let’s update the <strong>authMiddleware.ts</strong> to throw a <strong>AuthenticationError</strong> instead of general Error.</p><pre>import { Request, Response, NextFunction } from &quot;express&quot;;<br>import jwt, { JwtPayload } from &quot;jsonwebtoken&quot;;<br>import User from &quot;../models/User&quot;;<br>import asyncHandler from &quot;express-async-handler&quot;;<br>import { AuthenticationError } from &quot;./errorMiddleware&quot;;<br><br>const authenticate = asyncHandler(<br>  async (req: Request, res: Response, next: NextFunction) =&gt; {<br>    try {<br>      let token = req.cookies.jwt;<br><br>      if (!token) {<br>        throw new AuthenticationError(&quot;Token not found&quot;);<br>      }<br><br>      const jwtSecret = process.env.JWT_SECRET || &quot;&quot;;<br>      const decoded = jwt.verify(token, jwtSecret) as JwtPayload;<br><br>      if (!decoded || !decoded.userId) {<br>        throw new AuthenticationError(&quot;UserId not found&quot;);<br>      }<br><br>      const user = await User.findById(decoded.userId, &quot;_id name email&quot;);<br><br>      if (!user) {<br>        throw new AuthenticationError(&quot;User not found&quot;);<br>      }<br><br>      req.user = user;<br>      next();<br>    } catch (e) {<br>      throw new AuthenticationError(&quot;Invalid token&quot;);<br>    }<br>  }<br>);<br><br>export { authenticate };</pre><p>Now let’s create a sample API which needs <strong>protected access</strong>. For this we can create a <strong>GET</strong> request that retrieves user’s data for his/her profile. If you’re following the <a href="https://medium.com/@prabhashi.mm/create-a-simple-react-app-typescript-with-login-register-pages-using-create-react-app-e5c12dd6db53">series</a>, in the frontend application, once the user logs in, a request is sent to this API to retrieve user data. When our application grows, we’ll be implementing more protected APIs.</p><p>Create a <strong>userController.ts</strong> in <strong>controllers</strong> folder and add below code.</p><pre>import { Request, Response } from &quot;express&quot;;<br>import User from &quot;../models/User&quot;;<br><br>const getUser = async (req: Request, res: Response) =&gt; {<br>  const userId = req.user?._id;<br>  const user = await User.findById(userId, &quot;name email&quot;);<br><br>  if (!user) {<br>    res.status(400);<br>  }<br><br>  res.status(200).json(user);<br>};<br><br>export { getUser };</pre><p>Create a <strong>userRouter.ts</strong> in <strong>routes</strong> folder and add below code.</p><pre>import express from &quot;express&quot;;<br>import { getUser } from &quot;../controllers/userController&quot;;<br><br>const router = express.Router();<br><br>router.get(&quot;/:id&quot;, getUser);<br><br>export default router;</pre><p>Now, import the router in <strong>index.ts</strong> and expose it via <strong>/users</strong>. Here we have added the <strong>authenticate middleware </strong>to the <strong>/users</strong> route. So any request that tries to access routes in <strong>userRouter</strong> will first go through the middleware.</p><pre>import userRouter from &quot;./routes/userRouter&quot;;<br><br>app.use(&quot;/users&quot;, authenticate, userRouter);</pre><p>Now if we send a GET request to http://localhost:8000/users/{user_id}, you’ll get the data for your profile. We retrieve the user data based on the <strong>userId in the token</strong>. We can add a validation to the <strong>id</strong> parameter sent in the request to check if it’s the same as the id in the token (I haven’t done that here). But in any case, you <strong>shouldn’t</strong> retrieve user data based on the id sent in the url; since if the id belongs to someone else, you’ll be sending back those data, which <strong>must not</strong> be the case.</p><p>Install <strong>helmet</strong> package also and add it to the <strong>index.ts</strong> file. This secures the app by adding a set of response headers.</p><pre>npm i helmet</pre><p>The <strong>index.ts</strong> up to now should be as below.</p><pre>import express from &quot;express&quot;;<br>import authRouter from &quot;./routes/authRouter&quot;;<br>import connectUserDB from &quot;./connections/userDB&quot;;<br>import dotenv from &quot;dotenv&quot;;<br>import cors from &quot;cors&quot;;<br>import helmet from &quot;helmet&quot;;<br>import bodyParser from &quot;body-parser&quot;;<br>import cookieParser from &quot;cookie-parser&quot;;<br>import userRouter from &quot;./routes/userRouter&quot;;<br>import { authenticate } from &quot;./middleware/authMiddleware&quot;;<br>import { errorHandler } from &quot;./middleware/errorMiddleware&quot;;<br><br>dotenv.config();<br><br>interface UserBasicInfo {<br>  _id: string;<br>  name: string;<br>  email: string;<br>}<br><br>declare global {<br>  namespace Express {<br>    interface Request {<br>      user?: UserBasicInfo | null;<br>    }<br>  }<br>}<br><br>const app = express();<br>const port = process.env.PORT || 8000;<br>app.use(helmet());<br><br>app.use(<br>  cors({<br>    origin: &quot;http://localhost:3000&quot;,<br>    credentials: true,<br>  })<br>);<br><br>app.use(cookieParser());<br><br>app.use(bodyParser.json()); // To recognize the req obj as a json obj<br>app.use(bodyParser.urlencoded({ extended: true })); // To recognize the req obj as strings or arrays. extended true to handle nested objects also<br><br>app.listen(port, () =&gt; {<br>  console.log(`Server is running on port ${port}`);<br>});<br><br>app.use(authRouter);<br>app.use(&quot;/users&quot;, authenticate, userRouter);<br><br>app.use(errorHandler);<br><br>connectUserDB();</pre><p>Instead of accessing environmental variables using <strong><em>process.env</em></strong> each time, we can create a <strong>Config file </strong>and assign those to constants and use them in our files. I haven’t done that here though.</p><p>Now you have a Express application which handles register, login, logout and authentication of users when accessing protected routes!</p><p>Visit <a href="https://github.com/Prabashi/project-mgt-app-backend/tree/auth">this GitHub link</a> to view the full implementation up to now.</p><p>Follow me and stay tuned! If you have any questions, let me know in the comments!</p><h4>Next Steps</h4><p>We’ll handle <strong>authorization</strong> next for the frontend and backend applications, using <strong>Role Based Access Control</strong>.</p><p>Then we’ll continue to add more features to the application.</p><h4>Previous Steps</h4><p>Create a React application with Login / Register pages</p><p><a href="https://medium.com/@prabhashi.mm/create-a-simple-react-app-typescript-with-login-register-pages-using-create-react-app-e5c12dd6db53">Create a simple React app (TypeScript) with Login / Register pages using create-react-app</a></p><p>Manage your React application state using Redux Toolkit</p><p><a href="https://medium.com/@prabhashi.mm/manage-your-react-typescript-application-state-using-redux-toolkit-926d3b4abaa7">Manage your React (TypeScript) application state using Redux Toolkit</a></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f67be81da60" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/create-a-backend-application-using-express-typescript-and-handle-authentication-1f67be81da60">Create a Backend Application Using Express (TypeScript) and Handle Authentication</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage Your React (TypeScript) Application State Using Redux Toolkit]]></title>
            <link>https://blog.stackademic.com/manage-your-react-typescript-application-state-using-redux-toolkit-926d3b4abaa7?source=rss-58edc42004f------2</link>
            <guid isPermaLink="false">https://medium.com/p/926d3b4abaa7</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[react-router-6]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <dc:creator><![CDATA[Prabhashi Meddegoda]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 16:22:45 GMT</pubDate>
            <atom:updated>2023-09-20T10:43:11.462Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Redux</strong> is a JS library that can be used to manage the application state in your app in a centralized way. You’ll be retrieving the application state (the state that’s used globally or in multiple components) from a centralized location and will be performing centrally defined actions to update the state.</p><p>When your application grows, having a centralized way to manage the application state will be much easier. This is the reason we’re going to use Redux in our application.</p><p>Using the <strong>Redux Toolkit</strong> is the recommended way to implement state management using Redux. Unlike Redux, Redux Toolkit has <strong>less boilerplate code and is easy to use</strong>.</p><p>If you already have a frontend application created, you can use this article as a reference to use Redux Toolkit and axios in your application. If you don’t have one, you can follow the <a href="https://medium.com/@prabhashi.mm/create-a-simple-react-app-typescript-with-login-register-pages-using-create-react-app-e5c12dd6db53">previous article</a> of the series to create an application with Login/Register/Home pages.</p><h4>1. Setup Redux for the application</h4><p>Let’s start by running the below command to install Redux Toolkit and React Redux libraries.</p><pre>npm install @reduxjs/toolkit react-redux</pre><p>Create the following folders and files needed for the redux store, slices and hooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*fnHEoGYskUzWfexd7xt00g.png" /><figcaption>Folder / file structure for redux implementation</figcaption></figure><p>Include the following initial code to the slices.</p><p>authSlice.ts</p><pre>import { createSlice } from &quot;@reduxjs/toolkit&quot;;<br><br>const authSlice = createSlice({<br>  name: &quot;auth&quot;,<br>  initialState: &quot;&quot;,<br>  reducers: {},<br>});<br><br>export default authSlice.reducer;</pre><p>userSlice.ts</p><pre>import { createSlice } from &quot;@reduxjs/toolkit&quot;;<br><br>const userSlice = createSlice({<br>  name: &quot;user&quot;,<br>  initialState: &quot;&quot;,<br>  reducers: {},<br>});<br><br>export default userSlice.reducer;</pre><p>You can create <strong>separate slices for each of your feature</strong>, and import them to your <strong>store</strong>.</p><p>store.ts</p><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;<br>import authReducer from &quot;./slices/authSlice&quot;;<br>import userReducer from &quot;./slices/userSlice&quot;;<br><br>const store = configureStore({<br>  reducer: {<br>    auth: authReducer,<br>    user: userReducer,<br>  },<br>});<br><br>export type RootState = ReturnType&lt;typeof store.getState&gt;;<br>export type AppDispatch = typeof store.dispatch;<br><br>export default store;</pre><p>According to what we have defined above, we can access the state managed by authReducer through <strong><em>state.auth</em></strong> and state managed by userReducer through <strong><em>state.user</em></strong>.</p><p>Since we are using <strong>TypeScript</strong>, we need to export the types and create <strong>custom hooks</strong> using those types and redux-toolkit hooks (for dispatching events and accessing the store). Then we can use them in our codebase directly, otherwise we’ll have to define the types each time we use those hooks.</p><p>redux-hooks.ts</p><pre>import { useDispatch, useSelector } from &quot;react-redux&quot;;<br>import type { TypedUseSelectorHook } from &quot;react-redux&quot;;<br>import type { RootState, AppDispatch } from &quot;../store&quot;;<br><br>export const useAppDispatch: () =&gt; AppDispatch = useDispatch;<br>export const useAppSelector: TypedUseSelectorHook&lt;RootState&gt; = useSelector;</pre><p>We’ll use <strong><em>useAppDispatch()</em></strong> to dispatch an action. We can change our state by dispatching the actions we define. We’ll use <strong><em>useAppSelector()</em></strong> when we need to access the state in the store.</p><p>We need to pass our store as below, in order to access above hooks from our components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*-gMKe4OLsHIY-JOHd0wXXw.png" /><figcaption>Wrapping App component with the Provider for the store</figcaption></figure><h4>2. Using Thunk middleware and Axios to handle async API requests</h4><p>When we click Login / Register buttons, we need to send <strong>API requests</strong> to the backend, since those functionalities are handled in the backend. Based on the responses we receive, we can update our application state.</p><p>Let’s initiate the API requests and implement the required logic for the <strong>slices</strong> now. We need API requests to register, login and logout purposes. We’ll use <strong>axios</strong> for sending the API requests and use async <strong>Thunk middleware</strong> to handle the request logic (using Redux Toolkit’s <strong>createAsyncThunk</strong>).</p><p>Let’s install axios using below command.</p><pre>npm i axios</pre><p>We need to store the backend <strong>base url</strong>, in order to send the API requests. Let’s hardcode it in the <strong>contants.ts</strong> file. We can later change it to get the url from <strong>.env</strong> file (as environmental variables).</p><pre>export const BACKEND_BASE_URL = &quot;http://localhost:8000&quot;;</pre><p>Once we create the backend, we’ll expose it via port 8000, therefore I used the above as the backend base url.</p><p>Now, when the application grows, we’ll add more slices and we’ll use axios on these slices too. Therefore it’s better to create <strong>an instance of axios</strong> in one place and use it everywhere. Otherwise, if we need to change the default configurations of our axios requests, we’ll have to change everywhere.</p><p>We’ll have to set <strong>withCredentials</strong> property to <strong>true</strong>, so that axios will send any <strong>cookies</strong> associated. The authentication mechanism I’ll be implementing includes cookies and therefore I have set this to true for each request.</p><p>Create a <strong>api</strong> folder in src folder and create a <strong>axiosInstance.ts</strong> file and include below.</p><pre>import axios from &quot;axios&quot;;<br>import { BACKEND_BASE_URL } from &quot;../constants&quot;;<br><br>// Create an Axios instance with default options<br>const axiosInstance = axios.create({<br>  baseURL: BACKEND_BASE_URL,<br>  withCredentials: true,<br>});<br><br>export default axiosInstance;</pre><p>Now update the <strong>authSlice.ts</strong> with the following code.</p><pre>import { createSlice, createAsyncThunk, PayloadAction } from &quot;@reduxjs/toolkit&quot;;<br>import axiosInstance from &quot;../api/axiosInstance&quot;;<br><br>type User = {<br>  email: string;<br>  password: string;<br>};<br><br>type NewUser = User &amp; {<br>  name: string;<br>};<br><br>type UserBasicInfo = {<br>  id: string;<br>  name: string;<br>  email: string;<br>};<br><br>type UserProfileData = {<br>  name: string;<br>  email: string;<br>};<br><br>type AuthApiState = {<br>  basicUserInfo?: UserBasicInfo | null;<br>  userProfileData?: UserProfileData | null;<br>  status: &quot;idle&quot; | &quot;loading&quot; | &quot;failed&quot;;<br>  error: string | null;<br>};<br><br>const initialState: AuthApiState = {<br>  basicUserInfo: localStorage.getItem(&quot;userInfo&quot;)<br>    ? JSON.parse(localStorage.getItem(&quot;userInfo&quot;) as string)<br>    : null,<br>  userProfileData: undefined,<br>  status: &quot;idle&quot;,<br>  error: null,<br>};<br><br>export const login = createAsyncThunk(&quot;login&quot;, async (data: User) =&gt; {<br>  const response = await axiosInstance.post(&quot;/login&quot;, data);<br>  const resData = response.data;<br><br>  localStorage.setItem(&quot;userInfo&quot;, JSON.stringify(resData));<br><br>  return resData;<br>});<br><br>export const register = createAsyncThunk(&quot;register&quot;, async (data: NewUser) =&gt; {<br>  const response = await axiosInstance.post(<br>    &quot;/register&quot;,<br>    data<br>  );<br>  const resData = response.data;<br><br>  localStorage.setItem(&quot;userInfo&quot;, JSON.stringify(resData));<br><br>  return resData;<br>});<br><br>export const logout = createAsyncThunk(&quot;logout&quot;, async () =&gt; {<br>  const response = await axiosInstance.post(&quot;/logout&quot;, {});<br>  const resData = response.data;<br><br>  localStorage.removeItem(&quot;userInfo&quot;);<br><br>  return resData;<br>});<br><br>export const getUser = createAsyncThunk(<br>  &quot;users/profile&quot;,<br>  async (userId: string) =&gt; {<br>    const response = await axiosInstance.get(<br>      `/users/${userId}`<br>    );<br>    return response.data;<br>  }<br>);<br><br>const authSlice = createSlice({<br>  name: &quot;auth&quot;,<br>  initialState,<br>  reducers: {},<br>  extraReducers: (builder) =&gt; {<br>    builder<br>      .addCase(login.pending, (state) =&gt; {<br>        state.status = &quot;loading&quot;;<br>        state.error = null;<br>      })<br>      .addCase(<br>        login.fulfilled,<br>        (state, action: PayloadAction&lt;UserBasicInfo&gt;) =&gt; {<br>          state.status = &quot;idle&quot;;<br>          state.basicUserInfo = action.payload;<br>        }<br>      )<br>      .addCase(login.rejected, (state, action) =&gt; {<br>        state.status = &quot;failed&quot;;<br>        state.error = action.error.message || &quot;Login failed&quot;;<br>      })<br><br>      .addCase(register.pending, (state) =&gt; {<br>        state.status = &quot;loading&quot;;<br>        state.error = null;<br>      })<br>      .addCase(<br>        register.fulfilled,<br>        (state, action: PayloadAction&lt;UserBasicInfo&gt;) =&gt; {<br>          state.status = &quot;idle&quot;;<br>          state.basicUserInfo = action.payload;<br>        }<br>      )<br>      .addCase(register.rejected, (state, action) =&gt; {<br>        state.status = &quot;failed&quot;;<br>        state.error = action.error.message || &quot;Registration failed&quot;;<br>      })<br><br>      .addCase(logout.pending, (state) =&gt; {<br>        state.status = &quot;loading&quot;;<br>        state.error = null;<br>      })<br>      .addCase(logout.fulfilled, (state, action) =&gt; {<br>        state.status = &quot;idle&quot;;<br>        state.basicUserInfo = null;<br>      })<br>      .addCase(logout.rejected, (state, action) =&gt; {<br>        state.status = &quot;failed&quot;;<br>        state.error = action.error.message || &quot;Logout failed&quot;;<br>      })<br><br>      .addCase(getUser.pending, (state) =&gt; {<br>        state.status = &quot;loading&quot;;<br>        state.error = null;<br>      })<br>      .addCase(getUser.fulfilled, (state, action) =&gt; {<br>        state.status = &quot;idle&quot;;<br>        state.userProfileData = action.payload;<br>      })<br>      .addCase(getUser.rejected, (state, action) =&gt; {<br>        state.status = &quot;failed&quot;;<br>        state.error = action.error.message || &quot;Get user profile data failed&quot;;<br>      });<br>  },<br>});<br><br>export default authSlice.reducer;</pre><p>In the above code, we export 4 functions that initiate API requests; login, register, logout and getUser. Inside <strong><em>extraReducers</em></strong><em>,</em> we handle each case for the each function and set the state as needed. When the user registers / logs in, we save the user data receives from the responses to <strong><em>basicUserInfo</em></strong>. This is the state we use to validate if the user is <strong>authenticated or not</strong>. In logout, we make this state <strong><em>null</em></strong>.</p><p>When the user successfully registers / logs in, we save the <strong><em>userInfo</em></strong> in <strong>local storage</strong>, so that even when the user refreshes the page / revisits the app, we can access the local storage and confirm that the user is authenticated. When user logs out, we clear the userInfo in local storage.</p><p><strong><em>getUser()</em></strong> is implemented to demonstrate the authentication process in backend (we’ll implement this later). It retrieves the user’s profile data, if the user is authenticated.</p><p>I’m including a <strong>Logout</strong> button in <strong>Home.tsx</strong> until we implement a navigation bar later. I’ll include the Profile section in the same file<strong> for the moment</strong>.</p><pre>import React, { useEffect } from &quot;react&quot;;<br>import { Button } from &quot;@mui/material&quot;;<br>import { useAppDispatch, useAppSelector } from &quot;../hooks/redux-hooks&quot;;<br>import { getUser, logout } from &quot;../slices/authSlice&quot;;<br>import { useNavigate } from &quot;react-router-dom&quot;;<br><br>const Home = () =&gt; {<br>  const dispatch = useAppDispatch();<br>  const navigate = useNavigate();<br><br>  const basicUserInfo = useAppSelector((state) =&gt; state.auth.basicUserInfo);<br>  const userProfileInfo = useAppSelector((state) =&gt; state.auth.userProfileData);<br><br>  useEffect(() =&gt; {<br>    if (basicUserInfo) {<br>      dispatch(getUser(basicUserInfo.id));<br>    }<br>  }, [basicUserInfo]);<br><br>  const handleLogout = async () =&gt; {<br>    try {<br>      await dispatch(logout()).unwrap();<br>      navigate(&quot;/login&quot;);<br>    } catch (e) {<br>      console.error(e);<br>    }<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Home&lt;/h1&gt;<br>      &lt;h4&gt;Name: {userProfileInfo?.name}&lt;/h4&gt;<br>      &lt;h4&gt;Email: {userProfileInfo?.email}&lt;/h4&gt;<br>      &lt;Button variant=&quot;contained&quot; sx={{ mt: 3, mb: 2 }} onClick={handleLogout}&gt;<br>        Logout<br>      &lt;/Button&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Home;</pre><p>Here, if we have <strong><em>basicUserInfo</em> </strong>(meaning that the user is logged in), we dispatch <strong><em>getUser()</em></strong> to retrieve the profile information. If the user clicks logout button, <strong><em>logout()</em></strong> will be dispatched and the user will be navigated to login page. Please note the usage of useAppDispatch, useAppSelector, useNavigate, unwrap here.</p><p>Login.tsx</p><pre>import { LockOutlined } from &quot;@mui/icons-material&quot;;<br>import {<br>  Container,<br>  CssBaseline,<br>  Box,<br>  Avatar,<br>  Typography,<br>  TextField,<br>  Button,<br>  Grid,<br>} from &quot;@mui/material&quot;;<br>import { useState } from &quot;react&quot;;<br>import { Link } from &quot;react-router-dom&quot;;<br>import { useAppDispatch } from &quot;../hooks/redux-hooks&quot;;<br>import { login } from &quot;../slices/authSlice&quot;;<br><br>const Login = () =&gt; {<br>  const dispatch = useAppDispatch();<br><br>  const [email, setEmail] = useState(&quot;&quot;);<br>  const [password, setPassword] = useState(&quot;&quot;);<br><br>  const handleLogin = async () =&gt; {<br>    // This is only a basic validation of inputs. Improve this as needed.<br>    if (email &amp;&amp; password) {<br>      try {<br>        await dispatch(<br>          login({<br>            email,<br>            password,<br>          })<br>        ).unwrap();<br>      } catch (e) {<br>        console.error(e);<br>      }<br>    } else {<br>      // Show an error message.<br>    }<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;Container maxWidth=&quot;xs&quot;&gt;<br>        &lt;CssBaseline /&gt;<br>        &lt;Box<br>          sx={{<br>            mt: 20,<br>            display: &quot;flex&quot;,<br>            flexDirection: &quot;column&quot;,<br>            alignItems: &quot;center&quot;,<br>          }}<br>        &gt;<br>          &lt;Avatar sx={{ m: 1, bgcolor: &quot;primary.light&quot; }}&gt;<br>            &lt;LockOutlined /&gt;<br>          &lt;/Avatar&gt;<br>          &lt;Typography variant=&quot;h5&quot;&gt;Login&lt;/Typography&gt;<br>          &lt;Box sx={{ mt: 1 }}&gt;<br>            &lt;TextField<br>              margin=&quot;normal&quot;<br>              required<br>              fullWidth<br>              id=&quot;email&quot;<br>              label=&quot;Email Address&quot;<br>              name=&quot;email&quot;<br>              autoFocus<br>              value={email}<br>              onChange={(e) =&gt; setEmail(e.target.value)}<br>            /&gt;<br><br>            &lt;TextField<br>              margin=&quot;normal&quot;<br>              required<br>              fullWidth<br>              id=&quot;password&quot;<br>              name=&quot;password&quot;<br>              label=&quot;Password&quot;<br>              type=&quot;password&quot;<br>              value={password}<br>              onChange={(e) =&gt; {<br>                setPassword(e.target.value);<br>              }}<br>            /&gt;<br><br>            &lt;Button<br>              fullWidth<br>              variant=&quot;contained&quot;<br>              sx={{ mt: 3, mb: 2 }}<br>              onClick={handleLogin}<br>            &gt;<br>              Login<br>            &lt;/Button&gt;<br>            &lt;Grid container justifyContent={&quot;flex-end&quot;}&gt;<br>              &lt;Grid item&gt;<br>                &lt;Link to=&quot;/register&quot;&gt;Don&#39;t have an account? Register&lt;/Link&gt;<br>              &lt;/Grid&gt;<br>            &lt;/Grid&gt;<br>          &lt;/Box&gt;<br>        &lt;/Box&gt;<br>      &lt;/Container&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Login;</pre><p>Register.tsx</p><pre>import {<br>  Avatar,<br>  Box,<br>  Button,<br>  Container,<br>  CssBaseline,<br>  Grid,<br>  TextField,<br>  Typography,<br>} from &quot;@mui/material&quot;;<br>import { LockOutlined } from &quot;@mui/icons-material&quot;;<br>import { useState } from &quot;react&quot;;<br>import { Link } from &quot;react-router-dom&quot;;<br>import { useAppDispatch } from &quot;../hooks/redux-hooks&quot;;<br>import { register } from &quot;../slices/authSlice&quot;;<br><br>const Register = () =&gt; {<br>  const dispatch = useAppDispatch();<br><br>  const [name, setName] = useState(&quot;&quot;);<br>  const [email, setEmail] = useState(&quot;&quot;);<br>  const [password, setPassword] = useState(&quot;&quot;);<br><br>  const handleRegister = async () =&gt; {<br>    // This is only a basic validation of inputs. Improve this as needed.<br>    if (name &amp;&amp; email &amp;&amp; password) {<br>      try {<br>        await dispatch(<br>          register({<br>            name,<br>            email,<br>            password,<br>          })<br>        ).unwrap();<br>      } catch (e) {<br>        console.error(e);<br>      }<br>    } else {<br>      // Show an error message.<br>    }<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;Container maxWidth=&quot;xs&quot;&gt;<br>        &lt;CssBaseline /&gt;<br>        &lt;Box<br>          sx={{<br>            mt: 20,<br>            display: &quot;flex&quot;,<br>            flexDirection: &quot;column&quot;,<br>            alignItems: &quot;center&quot;,<br>          }}<br>        &gt;<br>          &lt;Avatar sx={{ m: 1, bgcolor: &quot;primary.light&quot; }}&gt;<br>            &lt;LockOutlined /&gt;<br>          &lt;/Avatar&gt;<br>          &lt;Typography variant=&quot;h5&quot;&gt;Register&lt;/Typography&gt;<br>          &lt;Box sx={{ mt: 3 }}&gt;<br>            &lt;Grid container spacing={2}&gt;<br>              &lt;Grid item xs={12}&gt;<br>                &lt;TextField<br>                  name=&quot;name&quot;<br>                  required<br>                  fullWidth<br>                  id=&quot;name&quot;<br>                  label=&quot;Name&quot;<br>                  autoFocus<br>                  value={name}<br>                  onChange={(e) =&gt; setName(e.target.value)}<br>                /&gt;<br>              &lt;/Grid&gt;<br><br>              &lt;Grid item xs={12}&gt;<br>                &lt;TextField<br>                  required<br>                  fullWidth<br>                  id=&quot;email&quot;<br>                  label=&quot;Email Address&quot;<br>                  name=&quot;email&quot;<br>                  value={email}<br>                  onChange={(e) =&gt; setEmail(e.target.value)}<br>                /&gt;<br>              &lt;/Grid&gt;<br>              &lt;Grid item xs={12}&gt;<br>                &lt;TextField<br>                  required<br>                  fullWidth<br>                  name=&quot;password&quot;<br>                  label=&quot;Password&quot;<br>                  type=&quot;password&quot;<br>                  id=&quot;password&quot;<br>                  value={password}<br>                  onChange={(e) =&gt; setPassword(e.target.value)}<br>                /&gt;<br>              &lt;/Grid&gt;<br>            &lt;/Grid&gt;<br>            &lt;Button<br>              fullWidth<br>              variant=&quot;contained&quot;<br>              sx={{ mt: 3, mb: 2 }}<br>              onClick={handleRegister}<br>            &gt;<br>              Register<br>            &lt;/Button&gt;<br>            &lt;Grid container justifyContent=&quot;flex-end&quot;&gt;<br>              &lt;Grid item&gt;<br>                &lt;Link to=&quot;/login&quot;&gt;Already have an account? Login&lt;/Link&gt;<br>              &lt;/Grid&gt;<br>            &lt;/Grid&gt;<br>          &lt;/Box&gt;<br>        &lt;/Box&gt;<br>      &lt;/Container&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Register;</pre><h4>3. Routes based on authentication status</h4><p>If the user is <strong>not authenticated</strong> (<strong><em>basicUserInfo</em></strong> is not available), then we should <strong>not</strong> allow the user to enter any of the <strong>protected routes</strong>. In our case, the Home page is restricted and therefore “/” route should <strong>only be available to authenticated users</strong>. If the user tries to enter Home page by updating the url in the address bar, Home <strong>must not render</strong> and the user should be <strong>redirected to Login page</strong>.</p><p>Let’s implement a separate component to handle this, and then update our <strong>routes</strong> to wrap the protected routes with the route of this component. We use the features of <strong>React Router V6</strong> to achieve this. We’ll use the same component to add a common layout later (eg: nav bar).</p><p>Create a <strong>layouts</strong> folder and add a <strong>ProtectedLayout.tsx</strong> file.</p><pre>import React from &quot;react&quot;;<br>import { Link, Outlet } from &quot;react-router-dom&quot;;<br>import { useAppDispatch, useAppSelector } from &quot;../hooks/redux-hooks&quot;;<br>import { Navigate } from &quot;react-router-dom&quot;;<br><br>const ProtectedLayout = () =&gt; {<br>  const basicUserInfo = useAppSelector((state) =&gt; state.auth.basicUserInfo);<br><br>  if (!basicUserInfo) {<br>    return &lt;Navigate replace to={&quot;/login&quot;} /&gt;;<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;Outlet /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default ProtectedLayout;</pre><p>Let’s create another file as <strong>DefaultLayout.tsx</strong> too to handle redirecting from Login/Register to Home page if the user is <strong>already logged in</strong>.</p><pre>import React from &quot;react&quot;;<br>import { Link, Outlet } from &quot;react-router-dom&quot;;<br>import { useAppDispatch, useAppSelector } from &quot;../hooks/redux-hooks&quot;;<br>import { Navigate } from &quot;react-router-dom&quot;;<br><br>const DefaultLayout = () =&gt; {<br>  const basicUserInfo = useAppSelector((state) =&gt; state.auth.basicUserInfo);<br><br>  if (basicUserInfo) {<br>    return &lt;Navigate replace to={&quot;/&quot;} /&gt;;<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;Outlet /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default DefaultLayout;</pre><p>Now let’s update the <strong>routes</strong> in the <strong>App.tsx</strong> to use respective layout.</p><pre>import React from &quot;react&quot;;<br>import { Routes, Route } from &quot;react-router-dom&quot;;<br>import Home from &quot;./pages/Home&quot;;<br>import Login from &quot;./pages/Login&quot;;<br>import Register from &quot;./pages/Register&quot;;<br>import DefaultLayout from &quot;./layouts/DefaultLayout&quot;;<br>import ProtectedLayout from &quot;./layouts/ProtectedLayout&quot;;<br><br>function App() {<br>  return (<br>    &lt;&gt;<br>      &lt;Routes&gt;<br>        &lt;Route element={&lt;DefaultLayout /&gt;}&gt;<br>          &lt;Route path=&quot;/login&quot; element={&lt;Login /&gt;} /&gt;<br>          &lt;Route path=&quot;/register&quot; element={&lt;Register /&gt;} /&gt;<br>        &lt;/Route&gt;<br>        &lt;Route element={&lt;ProtectedLayout /&gt;}&gt;<br>          &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;<br>        &lt;/Route&gt;<br>      &lt;/Routes&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App;</pre><p>Now you’re using Redux in your application, and handle API requests as well. If you’re following the series, this is it for the <strong>authentication part</strong> from <strong>frontend</strong> side.</p><p>Visit <a href="https://github.com/Prabashi/project-mgt-app-frontend/tree/auth">this GitHub link</a> to view the full implementation up to now.</p><p>Now, you’ll need to show <strong>error/success message alerts </strong>based on validations, response success / failure etc. We can implement this feature by using redux to handle the state of the alert. View the article <a href="https://medium.com/@prabhashi.mm/handle-notifications-in-your-react-application-typescript-using-redux-toolkit-and-use-a-custom-d2e1c9de9db2">here</a>.</p><p>Follow me and stay tuned! If you have any questions, let me know in the comments!</p><h4>Next Steps</h4><p>We’ll implement the backend using <strong>Express</strong> with <strong>TypeScript</strong>, and use <strong>MongoDB</strong> for the database.</p><p><a href="https://medium.com/@prabhashi.mm/create-a-backend-application-using-express-typescript-and-handle-authentication-1f67be81da60">Create a backend application using Express (TypeScript) and handle authentication</a></p><p>Finally, we’ll handle <strong>authorization</strong> for the frontend and backend applications, using <strong>Role Based Access Control</strong>.</p><p>Then we’ll continue to add more features to the application.</p><h4>Previous Steps</h4><p>Create a React app with Login / Register pages.</p><p><a href="https://medium.com/@prabhashi.mm/create-a-simple-react-app-typescript-with-login-register-pages-using-create-react-app-e5c12dd6db53">Create a simple React app (TypeScript) with Login / Register pages using create-react-app</a></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=926d3b4abaa7" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/manage-your-react-typescript-application-state-using-redux-toolkit-926d3b4abaa7">Manage Your React (TypeScript) Application State Using Redux Toolkit</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a simple React app (TypeScript) with Login / Register pages using create-react-app]]></title>
            <link>https://medium.com/@prabhashi.mm/create-a-simple-react-app-typescript-with-login-register-pages-using-create-react-app-e5c12dd6db53?source=rss-58edc42004f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5c12dd6db53</guid>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[material-ui]]></category>
            <dc:creator><![CDATA[Prabhashi Meddegoda]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 16:17:59 GMT</pubDate>
            <atom:updated>2023-09-15T16:35:09.876Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the first part of a series to implement the authentication and authorization process for a full stack application.</p><p>Here, we’ll create a React app using <strong>TypeScript</strong> and use <strong>MUI</strong> to create the UI, and <strong>React Router V6</strong> for client-side routing. I’m using <a href="https://create-react-app.dev/docs/getting-started">create-react-app</a> to create the React app.</p><h4>1. Creating the React app</h4><p>Open the terminal and cd to the folder where you want to create the app. Run below command. This will create a React app named “frontend” in TypeScript.</p><pre>npx create-react-app frontend --template typescript</pre><p>Open the application in VS Code. Open the terminal in VS Code and run below command.</p><pre>npm start</pre><p>Your app will be served in <a href="http://localhost:3000/">http://localhost:3000/</a></p><p>We don’t need some of the files created under our application folder. Remove these files (App.css, App.test.tsx, index.css, logo.svg) and your file structure should be as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*Fj2fmGaGLx3Qv7TvUyDPFg.png" /><figcaption>Initial folder structure</figcaption></figure><p>Remove the index.css import from <strong>index.tsx</strong> file. Update the <strong>App.tsx</strong> file as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*9sZE1NxuiWDbzMf6P-Ssiw.png" /><figcaption>Initial App.tsx file</figcaption></figure><p>Now we can continue with the implementation of the app.</p><h4>2. Client-side routing using React Router</h4><p>Run the following command to install the package.</p><pre>npm i react-router-dom</pre><p>Create 3 files under a <strong>pages</strong> <strong>folder</strong> as below, with basic implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ov2HbYjkWj7CH3s_r80L_Q.png" /><figcaption>Folder structure for pages</figcaption></figure><p>Import <strong>BrowserRouter</strong> in <strong>index.tsx</strong> file and wrap <strong>App</strong> component with it as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*AsrI7Xgnm5_AO5N2DA7Aeg.png" /><figcaption>BrowserRouter usage in index.tsx</figcaption></figure><p>In App.tsx file, import the components created for the pages and implement the routing as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*pFoMU4yg4OEYioK_0EV8QQ.png" /><figcaption>Routing in App.tsx</figcaption></figure><p>Now if you restart the app (npm start), you’ll be able to view each page by typing the links in the address bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnMuqFe5NH2tUBPA_hJ7EQ.png" /><figcaption>Basic frontend app in localhost</figcaption></figure><h4>3. UI implementation (Login / Register)</h4><p>I’m using MUI <a href="https://mui.com/material-ui/getting-started/templates/">free templates</a> for Login and Register pages, with a few updates.</p><p>First install mui, its dependencies and icons using below command.</p><pre>npm i @mui/material @emotion/react @emotion/styled @mui/icons-material</pre><p>Add below code to <strong>Login.tsx</strong> to implement the UI and to handle input field data.</p><pre>import { LockOutlined } from &quot;@mui/icons-material&quot;;<br>import {<br>  Container,<br>  CssBaseline,<br>  Box,<br>  Avatar,<br>  Typography,<br>  TextField,<br>  Button,<br>  Grid,<br>} from &quot;@mui/material&quot;;<br>import { useState } from &quot;react&quot;;<br>import { Link } from &quot;react-router-dom&quot;;<br><br>const Login = () =&gt; {<br>  const [email, setEmail] = useState(&quot;&quot;);<br>  const [password, setPassword] = useState(&quot;&quot;);<br><br>  const handleLogin = () =&gt; {};<br><br>  return (<br>    &lt;&gt;<br>      &lt;Container maxWidth=&quot;xs&quot;&gt;<br>        &lt;CssBaseline /&gt;<br>        &lt;Box<br>          sx={{<br>            mt: 20,<br>            display: &quot;flex&quot;,<br>            flexDirection: &quot;column&quot;,<br>            alignItems: &quot;center&quot;,<br>          }}<br>        &gt;<br>          &lt;Avatar sx={{ m: 1, bgcolor: &quot;primary.light&quot; }}&gt;<br>            &lt;LockOutlined /&gt;<br>          &lt;/Avatar&gt;<br>          &lt;Typography variant=&quot;h5&quot;&gt;Login&lt;/Typography&gt;<br>          &lt;Box sx={{ mt: 1 }}&gt;<br>            &lt;TextField<br>              margin=&quot;normal&quot;<br>              required<br>              fullWidth<br>              id=&quot;email&quot;<br>              label=&quot;Email Address&quot;<br>              name=&quot;email&quot;<br>              autoFocus<br>              value={email}<br>              onChange={(e) =&gt; setEmail(e.target.value)}<br>            /&gt;<br><br>            &lt;TextField<br>              margin=&quot;normal&quot;<br>              required<br>              fullWidth<br>              id=&quot;password&quot;<br>              name=&quot;password&quot;<br>              label=&quot;Password&quot;<br>              type=&quot;password&quot;<br>              value={password}<br>              onChange={(e) =&gt; {<br>                setPassword(e.target.value);<br>              }}<br>            /&gt;<br><br>            &lt;Button<br>              fullWidth<br>              variant=&quot;contained&quot;<br>              sx={{ mt: 3, mb: 2 }}<br>              onClick={handleLogin}<br>            &gt;<br>              Login<br>            &lt;/Button&gt;<br>            &lt;Grid container justifyContent={&quot;flex-end&quot;}&gt;<br>              &lt;Grid item&gt;<br>                &lt;Link to=&quot;/register&quot;&gt;Don&#39;t have an account? Register&lt;/Link&gt;<br>              &lt;/Grid&gt;<br>            &lt;/Grid&gt;<br>          &lt;/Box&gt;<br>        &lt;/Box&gt;<br>      &lt;/Container&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Login;</pre><p>Add below code to <strong>Register.tsx</strong> to implement the UI and to handle input field data.</p><pre>import {<br>  Avatar,<br>  Box,<br>  Button,<br>  Container,<br>  CssBaseline,<br>  Grid,<br>  TextField,<br>  Typography,<br>} from &quot;@mui/material&quot;;<br>import { LockOutlined } from &quot;@mui/icons-material&quot;;<br>import { useState } from &quot;react&quot;;<br>import { Link } from &quot;react-router-dom&quot;;<br><br>const Register = () =&gt; {<br>  const [name, setName] = useState(&quot;&quot;);<br>  const [email, setEmail] = useState(&quot;&quot;);<br>  const [password, setPassword] = useState(&quot;&quot;);<br><br>  const handleRegister = async () =&gt; {};<br><br>  return (<br>    &lt;&gt;<br>      &lt;Container maxWidth=&quot;xs&quot;&gt;<br>        &lt;CssBaseline /&gt;<br>        &lt;Box<br>          sx={{<br>            mt: 20,<br>            display: &quot;flex&quot;,<br>            flexDirection: &quot;column&quot;,<br>            alignItems: &quot;center&quot;,<br>          }}<br>        &gt;<br>          &lt;Avatar sx={{ m: 1, bgcolor: &quot;primary.light&quot; }}&gt;<br>            &lt;LockOutlined /&gt;<br>          &lt;/Avatar&gt;<br>          &lt;Typography variant=&quot;h5&quot;&gt;Register&lt;/Typography&gt;<br>          &lt;Box sx={{ mt: 3 }}&gt;<br>            &lt;Grid container spacing={2}&gt;<br>              &lt;Grid item xs={12}&gt;<br>                &lt;TextField<br>                  name=&quot;name&quot;<br>                  required<br>                  fullWidth<br>                  id=&quot;name&quot;<br>                  label=&quot;Name&quot;<br>                  autoFocus<br>                  value={name}<br>                  onChange={(e) =&gt; setName(e.target.value)}<br>                /&gt;<br>              &lt;/Grid&gt;<br><br>              &lt;Grid item xs={12}&gt;<br>                &lt;TextField<br>                  required<br>                  fullWidth<br>                  id=&quot;email&quot;<br>                  label=&quot;Email Address&quot;<br>                  name=&quot;email&quot;<br>                  value={email}<br>                  onChange={(e) =&gt; setEmail(e.target.value)}<br>                /&gt;<br>              &lt;/Grid&gt;<br>              &lt;Grid item xs={12}&gt;<br>                &lt;TextField<br>                  required<br>                  fullWidth<br>                  name=&quot;password&quot;<br>                  label=&quot;Password&quot;<br>                  type=&quot;password&quot;<br>                  id=&quot;password&quot;<br>                  value={password}<br>                  onChange={(e) =&gt; setPassword(e.target.value)}<br>                /&gt;<br>              &lt;/Grid&gt;<br>            &lt;/Grid&gt;<br>            &lt;Button<br>              fullWidth<br>              variant=&quot;contained&quot;<br>              sx={{ mt: 3, mb: 2 }}<br>              onClick={handleRegister}<br>            &gt;<br>              Register<br>            &lt;/Button&gt;<br>            &lt;Grid container justifyContent=&quot;flex-end&quot;&gt;<br>              &lt;Grid item&gt;<br>                &lt;Link to=&quot;/login&quot;&gt;Already have an account? Login&lt;/Link&gt;<br>              &lt;/Grid&gt;<br>            &lt;/Grid&gt;<br>          &lt;/Box&gt;<br>        &lt;/Box&gt;<br>      &lt;/Container&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Register;</pre><p>The UIs will be updated as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7TKcfOdyMRDFpMovnMH1g.png" /><figcaption>Login and Register pages</figcaption></figure><p>When we click Login / Register buttons, handleLogin() / handleRegister() functions will be called. We haven’t included anything inside those functions yet.</p><p>We have to <strong>validate</strong> the form fields and show an error message if any validation fails. If the validation is successful, we have to initiate an API request to the backend, in order to handle the functionalities.</p><p>Follow me and stay tuned! If you have any questions, let me know in the comments!</p><h4>Next Steps</h4><p>We’ll use <strong>Redux Toolkit</strong> for the state management of the application, and <strong>Axios</strong> to initiate the API requests (login, register, logout, profile).</p><p>Next we’ll handle error/success message alerts in a centralized way (using <strong>Redux Toolkit</strong> and <strong>MUI</strong> for the message UI).</p><p>After that we’ll update the frontend code with <strong>redirects</strong> and <strong>protected routes</strong> based on whether the user is logged in or not (authenticated or not).</p><p><a href="https://medium.com/@prabhashi.mm/manage-your-react-typescript-application-state-using-redux-toolkit-926d3b4abaa7">Manage your React (TypeScript) application state using Redux Toolkit</a></p><p>We’ll implement the backend using <strong>Express</strong> with <strong>TypeScript</strong>, and use <strong>MongoDB</strong> for the database.</p><p><a href="https://medium.com/@prabhashi.mm/create-a-backend-application-using-express-typescript-and-handle-authentication-1f67be81da60">Create a backend application using Express (TypeScript) and handle authentication</a></p><p>Finally, we’ll handle <strong>authorization</strong> for the frontend and backend applications, using <strong>Role Based Access Control</strong>.</p><p>Then we’ll continue to add more features to the application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5c12dd6db53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD Pipeline to publish a web app to GitHub Pages using GitHub Actions Workflow]]></title>
            <link>https://medium.com/@prabhashi.mm/ci-cd-pipeline-to-publish-a-web-app-to-github-pages-using-github-actions-workflow-bf73de51facd?source=rss-58edc42004f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf73de51facd</guid>
            <category><![CDATA[client-side-routing]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[github-pages]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Prabhashi Meddegoda]]></dc:creator>
            <pubDate>Wed, 30 Aug 2023 09:17:35 GMT</pubDate>
            <atom:updated>2023-09-15T16:40:26.052Z</atom:updated>
            <content:encoded><![CDATA[<p>You can use <strong>GitHub Pages</strong> to host your website / web application. If your application needs a build process to generate the static files, you can use <strong>GitHub Actions Workflow</strong> to automate the whole process of building and deploying to GitHub Pages.</p><p>Once you have automated the process, each time a commit is pushed from local to the GitHub repo, the workflow will be triggered and the website / web app will be updated automatically.</p><p>First, you need to add your codebase to a GitHub repository if you haven’t done already. If you are using the <strong>GitHub free version</strong>, your repository needs to be <strong>public</strong> in order to use GitHub Pages.</p><h4>Publishing static content to GitHub Pages</h4><p>If your codebase does not need a build process to generate the static content (in other words, if your codebase includes the static files itself), you can simply follow below steps to publish your website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AM_ax3qE08otn2DoEaTrgQ.png" /><figcaption>GitHub Settings</figcaption></figure><ol><li>Go to your GitHub repository (make sure the repo is public, if you are using GitHub Free version)</li><li>Go to the <strong>Settings</strong> tab. Select the <strong>Pages</strong> tab under the <strong>Code and automation</strong> section in the sidebar.</li><li>Select the <strong>Deploy from a branch</strong> option from the <strong>Source</strong> dropdown.</li><li>Select your branch and the source folder and save.</li><li>Your website will be deployed within a few minutes and you can refresh your current page (if not automatically updated) and view the <strong>View site</strong> link. The site link will be in the format of <strong>https://&lt;github-username&gt;.github.io/&lt;repo-name&gt;/</strong></li><li>Now try pushing a new code change to the repo. You’ll see the website is updated within a few minutes with your latest changes.</li></ol><p>If you need any customisation or additional steps, you can use GitHub Actions to create a workflow.</p><h4>GitHub Actions and Workflows</h4><p>You can use <strong>GitHub Actions</strong> to create <strong>workflows</strong> to automate the processes such as <strong>CI / CD</strong>. You can implement the workflow with CI / CD to host your application in Azure / AWS etc if you need to. In this article, we’ll deploy the application to <strong>GitHub Pages</strong>.</p><p>You can use a workflow to build, test and deploy a <strong>React application</strong>. If you’re using a <strong>static site generator</strong> such as MkDocs, the process will be similar, but you’ll have to update the workflow to meet your requirements.</p><h4>Publishing a React application to GitHub Pages</h4><ol><li>Go to your GitHub repository (make sure the repo is public, if you are using GitHub Free version)</li><li>Go to the <strong>Settings</strong> tab. Select the <strong>Pages</strong> tab under the <strong>Code and automation</strong> section in the sidebar.</li><li>Select the <strong>GitHub Actions </strong>option from the <strong>Source</strong> dropdown.</li><li>Go to the <strong>Actions</strong> tab <strong>or</strong> click on the <strong>browse all workflows</strong> link that appear below the Source dropdown. There’s a list of predefined workflows which you can configure based on the technologies you use. You can choose to setup a workflow by yourself as well.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TErvhawaC2V35KXoXzPHgA.png" /><figcaption>GitHub Actions</figcaption></figure><p>Following is a workflow that can be used to build, test and deploy a React application to GitHub pages. This workflow will be triggered each time a commit is pushed / a PR is created to the main branch.</p><pre>name: CI<br><br>on:<br>  push:<br>    branches: [ &quot;main&quot; ]<br>  pull_request:<br>    branches: [ &quot;main&quot; ]<br><br>env:<br>  CI: false<br><br>jobs:<br>  build:<br><br>    runs-on: ubuntu-latest<br>    environment:<br>      name: github-pages<br>      url: ${{ steps.deployment.outputs.page_url }}<br>    <br>    permissions:<br>      contents: &#39;read&#39;<br>      id-token: &#39;write&#39;<br>      pages: &#39;write&#39;<br>      actions: &#39;write&#39;<br>      checks: &#39;write&#39;<br>      deployments: &#39;write&#39;<br>    strategy:<br>      matrix:<br>        node-version: [18.x]<br>        # See supported Node.js release schedule at https://nodejs.org/en/about/releases/<br><br>    steps:<br>    - uses: actions/checkout@v3<br>    - name: Use Node.js ${{ matrix.node-version }}<br>      uses: actions/setup-node@v3<br>      with:<br>        node-version: ${{ matrix.node-version }}<br>        cache: &#39;npm&#39;<br>    - name: Install dependencies<br>      # Using npm ci is generally faster than running npm i because it caches dependencies<br>      run: |<br>        npm ci<br>    - name: Build the app<br>      run: |<br>        npm run build<br>    - name: Run component tests<br>      run: |<br>        npm run test<br>        <br>    - name: Setup Pages<br>      uses: actions/configure-pages@v3<br>    - name: Upload artifact<br>      uses: actions/upload-pages-artifact@v1<br>      with:<br>        # Upload build directory content<br>        path: &#39;build/&#39;<br>    - name: Deploy to GitHub Pages<br>      id: deployment<br>      uses: actions/deploy-pages@v1<br>      env:  <br>        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}</pre><p>We have used predefined <strong>actions</strong> here in this workflow. They are in the format of <strong><em>actions/&lt;action_name&gt;@&lt;version&gt;</em></strong> in the above workflow. You can view more details about these actions by visiting to <a href="https://github.com/marketplace?type=actions">GitHub Marketplace</a>.</p><p>After adding the workflow, commit the changes to the main branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-3ZbXqyjZCDTQbDNY7fFQ.png" /><figcaption>Workflow yaml file</figcaption></figure><p>If you go to <strong>Actions</strong> tab now, you can see the workflow is running.</p><p>But there’s one more thing you need to do in order to successfully host your React application. You have to update your <strong>package.json</strong> file with the <strong>homepage </strong>set to the <strong>base url of the application</strong> as shown below (update the value of <strong>github-username</strong> and <strong>repo-name</strong> with yours). This is because, the create-react-app uses the <strong>homepage</strong> field to determine the root URL when building the application.</p><pre>{<br>  &quot;name&quot;: &quot;my-portfolio&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;homepage&quot;: &quot;https://&lt;github-username&gt;.github.io/&lt;repo-name&gt;/&quot;,<br>  &quot;dependencies&quot;: {</pre><p>Now commit and push the above change to your repo (you’ll have to pull the changes to your local first). A new workflow will be triggered and you can view its status and flow in the <strong>Actions</strong> tab.</p><p>Once it is successfully completed, you can go this link and view your published application. <strong>https://&lt;github-username&gt;.github.io/&lt;repo-name&gt;/. </strong>You can find the link in the <strong>Actions</strong> page or in <strong>Settings </strong>page<strong> -&gt; Pages </strong>tab also.</p><p>But, if you’re using <strong>client-side routing</strong> in your <strong>React application</strong> (using <strong>react-router-dom</strong>), then the routing will not work as expected. The reason is, GitHub server doesn’t know such a path exists since it’s only a client-side routing. Therefore it’ll show a 404 page.</p><p>As a workaround for this, you can use <a href="https://reactrouter.com/en/main/router-components/hash-router"><strong>HashRouter</strong></a> from <strong>react-router-dom</strong> to wrap your routes instead of using BrowserRouter. This adds the route to the <strong># portion</strong> in your url, instead of sending it to the server.</p><p>Now your application should be successfully published to GitHub Pages! Since the CI / CD pipeline is also implemented using the workflow, each time you push a commit / create a PR to main branch, your application will be built, tested and deployed.</p><h4>Conclusion</h4><ul><li>If your codebase already consists of static files, you can simply configure the repo to publish the website to GitHub Pages and deploy each time a change is added.</li><li>If you need a build process such as in the case of static site generators or React applications, you can create GitHub Actions Workflow to automate the CI / CD process.</li><li>If you’re hosting a React application and uses client-side routing, you’ll have to do some changes in the codebase to make it work properly.</li></ul><p>Follow me and stay tuned! If you have any questions, let me know in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf73de51facd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>