diff --git a/docs/UI-UX/README.md b/docs/UI-UX/README.md index 56475b1d8..26eb0cb0c 100644 --- a/docs/UI-UX/README.md +++ b/docs/UI-UX/README.md @@ -1,5 +1,7 @@ # User Interface and User Experience Engineering +## Introduction + Also known as _UI/UX_, _Front End Development_, or _Web Development_, user interface and user experience engineering is a broad topic and encompasses many different aspects of modern application development. When a user interface is required, ISE primarily develops a **web application**. Web apps can be built in a variety of ways with many different tools. ## Goal @@ -43,17 +45,106 @@ After defining these personas it is clear that whatever the solution is, it requ After defining the _desired outcomes_ as well as the _personas_, the next step in the design process is to begin conducting [Trade Studies](./../design/design-reviews/trade-studies/README.md) for potential solutions. The first trade study should be high-level and solution oriented. It will utilize the results of previous steps and propose multiple solutions for achieving the desired outcomes with the listed personas in mind. Continuing with the library example, this first trade study may compare various application solutions such as automated emails or text messages, an RSS feed, or an user interface application. There are pros and cons for each solution both from an user experience and a developer experience perspective, but at this stage it is important to focus on the users. After arriving on the best solution, the next trade study can dive into different implementation methods. It is in this subsequent trade studies that developer experience becomes more important. -The benefit of building software applications is that there are truly infinite ways to build something. A team can use the latest shiny tools, or they can utilize the tried-and-tested ones. It is for this reason that focussing completely on the user until a solution is defined is better than obsessing over technology choices. Within ISE, we often reach for tools such as the [React](https://reactjs.org/) framework. React is a great tool when wielded by an experienced team. Otherwise, it can create more hurdles than it is worth. Keep in mind that even if _you_ feel capable with React, the rest of your team and your customer's dev team needs to as well. Some other great options to consider when building a proof-of-concept or minimum-viable-product are: +## Design Ops + +Design Ops, short for Design Operations, is a practice that focuses on optimizing and streamlining the design process within an organization. For software engineers, understanding Design Ops can significantly enhance collaboration with design and engineering teams and improve the overall efficiency of product development. + +### Key Components of Design Ops + +1. **Establishing clear processes and workflows for design tasks:** + - Utilizing project management tools like [Azure DevOps](https://azure.microsoft.com/en-us/services/devops/), [Jira](https://www.atlassian.com/software/jira), [Trello](https://trello.com/), or [Asana](https://asana.com/) to track design progress and dependencies. + +2. **Collaboration Tools**: + - Leveraging tools like [Figma](https://www.figma.com/), or [Sketch](https://www.sketch.com/) (Mac OS only) for design collaboration. + - Ensuring seamless handoff between design and development through tools like [Zeplin](https://zeplin.io/) or [InVision](https://www.invisionapp.com/). + - Validating Product Owner approved designs to be sent for development, and prevent design changes once approved. + +3. **Design Systems**: + - Creating and maintaining a design system that includes reusable components, style guides, and design tokens. + - Promoting consistency and efficiency by using shared design assets. + - For most projects within ISE we use [Fluent UI](https://developer.microsoft.com/en-us/fluentui#/controls/webcomponents) to handle most projects, this enables rapid development that allow for web application re-use on non-customer engagements or _white label_ applications. + - Other Design Systems used by customers include: [Google's Material Design](https://mui.com/material-ui/), + +4. **Documentation**: + - Documenting design decisions, guidelines, and best practices. + - Ensuring that all team members have access to up-to-date design documentation. + - Frameworks like [Storybook.js](https://storybook.js.org/) can create _Swagger like_ documentation for UI components. + +5. **Feedback Loops**: + - Establishing regular design reviews (including product owners and end users) and feedback sessions. + - Encouraging iterative improvements on designs and UI/UX code implementation based on user and stakeholder feedback. + +6. **Metrics and KPIs**: + - Defining key performance indicators (KPIs) to measure the effectiveness of design processes. + - Using metrics to identify areas for improvement and track progress over time. + - __For long-term projects:__ Incorporate _A/B testing_ for better user experiences, and enhancements to the solution. + +### Benefits of Design Ops for Software Engineers and Product Owners + +- **Improved Collaboration**: Clear processes and tools facilitate better communication and collaboration between designers and developers. +- **Consistency**: Design systems ensure a consistent user experience across different parts of the application. +- **Efficiency**: Streamlined workflows and reusable components reduce redundant work and speed up development. +- **Quality**: Regular feedback loops and documentation help maintain high design standards and improve the final product. + +By integrating Design Ops into the development process, software engineers can work more effectively with design teams, leading to better-designed products and a more efficient development cycle. It also builds trust with a customer to better ideate on what the final outcome of a project could be. + +## Establishing a web application's architecture + +The benefit of building software applications is that there are truly infinite ways to build something. A team can use the latest shiny tools, or they can utilize the tried-and-tested ones. It is for this reason that focussing completely on the user until a solution is defined is better than obsessing over technology choices. + +When choosing a front-end framework or library, consider the project's complexity, performance, and scalability needs. Evaluate the team's expertise with potential options to ensure efficient development. Assess long-term maintainability and community support. Conduct [Trade Studies](./../design/design-reviews/trade-studies/README.md) to weigh pros and cons, focusing on alignment with project goals and user experience. This thorough analysis helps balance innovation with practicality. + + +### Some platforms/frameworks to consider when planning a project: 1. HTML/CSS/JavaScript - Back to the basics! Start with a single **index.html**, include a popular CSS framework such as [Bootstrap](https://getbootstrap.com/) using their CDN link, and start prototyping! - Rarely will you have to support legacy browsers; thus, you can rely on modern JavaScript language features! No need for build tools or even TypeScript (did you know you can [type check JavaScript](https://www.typescriptlang.org/docs/handbook/intro-to-js-ts.html)). + - For static _vanilla_ websites like this; we still recommend a build system like [Vite](https://vitejs.dev/) to build and manage assets for deployment. +1. React + - [React](https://reactjs.org/) allows for the creation of reusable UI components, and is used for most projects in ISE. + - Ideal for projects that require a dynamic and responsive user interface. + - Works well with a variety of state management libraries like Redux or Context API. + - Has a massive 3rd party library support. + - Supports [Fluent UI](https://developer.microsoft.com/en-us/fluentui#/controls/webcomponents) directly. + - Has [extensive documentation for integrating with Azure on Microsoft Learn](https://learn.microsoft.com/en-us/training/paths/react/). +1. Angular + - A robust framework for building client-side applications. [Angular](https://angular.dev/) provides a comprehensive solution with built-in features like dependency injection, routing, and state management. + - Ideal for large-scale applications where maintainability and scalability are crucial. + - Better Unit Testing support out of the box than React. + - __Angular has no support for Fluent UI, and has tight integration with Google Cloud Platform.__ +1. Blazor + - A framework for building interactive web UIs using C# instead of JavaScript. [Blazor](https://dotnet.microsoft.com/en-us/apps/aspnet/web-apps/blazor) allows you to share code between the client and server. + - Great for teams already familiar with the .NET ecosystem. + - Fantastic platform where UI elements can be fully hosted and served server-side, adding security. + - [Supports Fluent UI with its own supported library](https://www.fluentui-blazor.net/). +1. ASP.NET Core + - A mature framework for building server-side web applications. [ASP.NET Core](https://dotnet.microsoft.com/en-us/apps/aspnet) supports MVC architecture, making it easier to manage complex applications. + - Suitable for enterprise-level applications requiring robust security and performance. **(Great for Government web applications where security is paramount)** +1. Next.js + - A React-based framework that enables server-side rendering and static site generation. [Next.js](https://nextjs.org/) improves performance and SEO. + - Great for building fast, scalable web applications with a focus on developer experience. + - Provides built-in support for API routes, making it easier to build full-stack applications. + - __Recommended by Meta going forward rather than use create-react-app.__ + - Next.js is very heavy in terms of features, and it doesn't allow for re-use in non-Next.js applications like create-react-app, React-Native, or Electron based apps. +1. Svelte + - [Svelte](https://svelte.dev/) is a modern framework that shifts much of the work to compile time, resulting in highly optimized and performant applications. + - Ideal for projects where performance is critical and you want to minimize the amount of JavaScript sent to the client. + - Svelte's syntax is simple and intuitive, making it easy to learn and use. +1. Solid + - [Solid](https://solidjs.com/) is a declarative JavaScript library for building user interfaces, focusing on fine-grained reactivity. + - Great for projects that require high performance and efficient updates, as Solid compiles to highly optimized JavaScript. + - Solid's API is similar to React, making it easier for developers familiar with React to transition. 1. Web Component frameworks - - Web Components are now standardized in all modern browsers - - Microsoft has their own, stable & actively-maintained framework, [Fast](https://www.fast.design/) - -For more information of choosing the right implementation tool, read the [Recommended Technologies](./recommended-technologies.md) document. - -Continue reading the [Trade Study](./../design/design-reviews/trade-studies/README.md) section of this site for more information on completing this step in the design process. - -After iterating through multiple trade study documents, this design process can be considered complete! With an agreed upon solution and implementation in mind, it is now time to begin development. A natural continuation of the design process is to get users (or stakeholders) involved as early as possible. Constantly look for design and usability feedback, and utilize this to improve the application as it is being developed. + - Web Components are now standardized in all modern browsers. + - Microsoft has their own, stable & actively-maintained framework, [Fast](https://www.fast.design/). +1. HTMX + - [HTMX](https://htmx.org/) allows you to access modern browser features directly from HTML, making it easier to build dynamic web applications without relying heavily on JavaScript. + - Ideal for projects that require a simpler, more declarative approach to adding interactivity to web pages. + - Works well with server-side frameworks and can be integrated into existing projects with minimal effort. + +### Further information + +> For more information of utilizing any of these frameworks/platforms, read the [Recommended Technologies](./recommended-technologies.md) document. +> +> Continue reading the [Trade Study](./../design/design-reviews/trade-studies/README.md) section of this site for more information on completing this step in the design process. diff --git a/docs/UI-UX/images/vite-wizard.png b/docs/UI-UX/images/vite-wizard.png new file mode 100644 index 000000000..a3beb79b7 Binary files /dev/null and b/docs/UI-UX/images/vite-wizard.png differ diff --git a/docs/UI-UX/recommended-technologies.md b/docs/UI-UX/recommended-technologies.md index 48602feff..b537c116b 100644 --- a/docs/UI-UX/recommended-technologies.md +++ b/docs/UI-UX/recommended-technologies.md @@ -1,5 +1,38 @@ # Recommended Technologies +## Table of Contents + +- [TypeScript](#typescript) + - [Guidance on types and interfaces](#guidance-on-types-and-interfaces) + - [Example](#example) +- [Bootstrapping Web Projects](#bootstrapping-web-projects) + - [Vite](#vite) + - [Documentation & Recommended Resources](#documentation--recommended-resources) + - [Installing Vite](#installing-vite) + - [Bootstrapping a project](#bootstrapping-a-project) +- [React](#react) + - [Quick note on create-react-app](#quick-note-on-create-react-app) + - [Documentation & Using older React coding patterns](#documentation--using-older-react-coding-patterns) + - [Best Practices to Organize Your React Codebase](#best-practices-to-organize-your-react-codebase) + - [Project Structure](#project-structure) + - [Key Directories and Files](#key-directories-and-files) + - [Directory Best Practices](#directory-best-practices) + - [Using React with Entra ID](#using-react-with-entra-id) + - [Resources](#resources) +- [Managing Secrets with Environmental Variables in React Projects Using Vite](#managing-secrets-with-environmental-variables-in-react-projects-using-vite) + - [Setting Up Environmental Variables](#setting-up-environmental-variables) + - [Best Security Practices](#best-security-practices) + - [Resources](#resources-1) +- [Common Security Pitfalls in React Applications](#common-security-pitfalls-in-react-applications) + - [Resources](#resources-2) +- [Incorporating Axios for REST API Calls in React with Bearer Tokens and MSAL](#incorporating-axios-for-rest-api-calls-in-react-with-bearer-tokens-and-msal) + - [Setting Up Axios](#setting-up-axios) + - [Making API Calls](#making-api-calls) + - [Resources](#resources-3) + + +--- + The purpose of this page is to review the commonly selected technology options when developing user interface applications. To reiterate from the general guidance section: > Keep in mind that like all software, there is no "right way" to build a user interface application. Leverage and trust your team's or your customer's experience and expertise for the best development experience. @@ -11,25 +44,82 @@ Additionally, while some of these technologies are presented as alternate option > TypeScript is JavaScript with syntax for types. TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale. > [typescriptlang.org](https://www.typescriptlang.org/) -TypeScript is highly recommended for all new web application projects. The stability it provides for teams is unmatched, and can make it easier for folks with C# backgrounds to work with web technologies. +TypeScript is __highly recommended__ for all new web application projects. The stability it provides for teams is unmatched, and can make it easier for folks with C# backgrounds to work with web technologies. There are many ways to integrate TypeScript into a web application. The easiest way to get started is by reviewing the [TypeScript Tooling in 5 Minutes](https://www.typescriptlang.org/docs/handbook/typescript-tooling-in-5-minutes.html) guide from the official TypeScript docs. The other sections on this page contain information regarding integration with TypeScript. -## React -React is a framework developed and maintained by Facebook. React is used throughout Microsoft and has a vast open source community. +## Guidance on types and interfaces -### Documentation & Recommended Resources +In TypeScript, both `type` and `interface` can be used to define the shape of an object. However, it is generally recommended to prefer `type` over `interface` for most use cases due to its simplicity and flexibility. It also prevents inheritance when using a `type` which can badly scale overtime unless explicitly declared. -One can expect to find a multitude of guides, answers, and posts on how to work with React; don't take everything at face value. The best place to review React concepts is the React documentation. From there, you can review articles from various sources such as [React Community Articles](https://reactjs.org/community/articles.html), [Kent C Dodd's Blog](https://kentcdodds.com/blog?q=react), [CSS Tricks Articles](https://css-tricks.com/?s=react), and [Awesome React](https://github.com/enaqx/awesome-react). +### Example -The React API has changed dramatically over time. Older resources may contain solutions or patterns that have since been changed and improved upon. Modern React development uses the [React Hooks](https://reactjs.org/docs/hooks-intro.html) pattern. Rarely will you have to implement something using [React Class](https://reactjs.org/docs/react-component.html) pattern. If you're reading an article/answer/docs that instruct you to use the class pattern you may be looking at an out-of-date resource. +Using `type`: + +```typescript +type User = { + name: string; + age: number; +}; +``` + +Using `interface`: + +```typescript +interface User { + name: string; + age: number; +} +``` + +While both achieve the same result, `type` can also be used for other TypeScript features like union types, which makes it more versatile. + +For more details, refer to the [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html). + +## Bootstrapping Web Projects + +There are many different ways to bootstrap web applications. Two great tool sets to use are [create-react-app](https://create-react-app.dev/) and [vite](https://vitejs.dev/guide). + +### Vite + +[Vite](https://vitejs.dev/) is a modern build tool that provides a fast and optimized development experience for engineers. It leverages native ES modules in the browser to deliver lightning-fast hot module replacement (HMR) and instant server start. [Vite](https://vitejs.dev/) also offers a highly optimized build process using [Rollup](https://rollupjs.org/introduction/), ensuring efficient and performant production builds. By simplifying the setup and configuration, [Vite](https://vitejs.dev/) allows developers to focus more on writing code and less on tooling, making it an excellent choice for modern web development. For more details, visit the [Vite project](https://vitejs.dev/) and [Vite GitHub repository](https://github.com/vitejs/vite). + +#### Documentation & Recommended Resources + +- [Vite Documentation](https://vitejs.dev/guide/) +- [Vite GitHub Repository](https://github.com/vitejs/vite) +- [Vite Rollup Plugin](https://vitejs.dev/guide/api-plugin.html) +- [Vite HMR](https://vitejs.dev/guide/features.html#hot-module-replacement) +- [Vite Configuration](https://vitejs.dev/config/) +- [Vite Plugins](https://vitejs.dev/plugins/) +- [Vite Troubleshooting](https://vitejs.dev/guide/troubleshooting.html) + +From [Scaffolding your First Vite Project](https://vitejs.dev/guide/#scaffolding-your-first-vite-project) + +##### Installing Vite + +```sh +# Install Vite +npm install -D vite +``` +##### Bootstrapping a project +```sh +npm create vite@latest +``` +This will start a CLI interface that will create multiple types of projects that Vite supports: React, Angular, Svelte, Solid, Vue, or even Vanilla HTML and JavaScript. -### Bootstrapping +![Vite Wizard](./images/vite-wizard.png "Vite Wizard") -There are many different ways to bootstrap a React application. Two great tool sets to use are [create-react-app](https://create-react-app.dev/) and [vite](https://vitejs.dev/guide). -#### create-react-app +## React + +React is a framework developed and maintained by Meta (Formerly Facebook). React is used throughout Microsoft's product stack and has a vast open source community. + +### Quick note on create-react-app + +> __create-react-app is deprecated as of January 2023 and should be avoided for new projects.__ It is recommended to use more modern tools like [Vite](#vite) for better performance and flexibility. For more details, refer to the [official React blog](https://react.dev/blog) and [Vite documentation](https://vitejs.dev/guide/why.html). + From [Adding TypeScript](https://create-react-app.dev/docs/adding-typescript/) @@ -37,14 +127,312 @@ From [Adding TypeScript](https://create-react-app.dev/docs/adding-typescript/) npx create-react-app my-app --template typescript ``` -#### Vite +### Documentation & Using older React coding patterns -From [Scaffolding your First Vite Project](https://vitejs.dev/guide/#scaffolding-your-first-vite-project) +One can expect to find a multitude of guides, answers, and posts on how to work with React; don't take everything at face value. The best place to review React concepts is the React documentation. From there, you can review articles from various sources such as [React Community Articles](https://reactjs.org/community/articles.html), [Kent C Dodd's Blog](https://kentcdodds.com/blog?q=react), [CSS Tricks Articles](https://css-tricks.com/?s=react), and [Awesome React](https://github.com/enaqx/awesome-react). -```sh -# npm 6.x -npm init vite@latest my-app --template react-ts +The React API has changed dramatically over time. Older resources may contain solutions or patterns that have since been changed and improved upon. Modern React development uses the [React Hooks](https://reactjs.org/docs/hooks-intro.html) pattern. Rarely will you have to implement something using [React Class](https://reactjs.org/docs/react-component.html) pattern. If you're reading an article/answer/docs that instruct you to use the class pattern you may be looking at an out-of-date resource. + + +## Best Practices to Organize Your React Codebase + +Organizing your React codebase effectively can improve maintainability, scalability, and collaboration. Here are some best practices to follow: + +#### Project Structure + +A well-structured project can make it easier to navigate and manage your codebase. Here's a recommended project structure: + +``` +my-react-app/ +├── public/ +│ ├── index.html +│ └── assets/ +│ ├── favicon.ico +│ └── logo.png +├── src/ +│ ├── assets/ +│ │ └── styles/ +│ │ └── main.css +│ ├── components/ +│ │ ├── Button/ +│ │ │ ├── Button.tsx +│ │ │ └── Button.test.tsx +│ │ └── Header/ +│ │ ├── Header.tsx +│ │ └── Header.test.tsx +│ ├── hooks/ +│ │ └── useAuth.ts +│ ├── pages/ +│ │ ├── Home/ +│ │ │ ├── Home.tsx +│ │ │ └── Home.test.tsx +│ │ └── About/ +│ │ ├── About.tsx +│ │ └── About.test.tsx +│ ├── services/ +│ │ └── apiClient.ts +│ ├── types/ +│ │ └── index.ts +│ ├── utils/ +│ │ └── helpers.ts +│ ├── App.tsx +│ ├── index.tsx +│ └── vite-env.d.ts +├── .env +├── .gitignore +├── package.json +├── tsconfig.json +└── vite.config.ts +``` + +#### Key Directories and Files + +- **public/**: Contains static assets like HTML and images. +- **src/**: Contains the source code of your application. + - **assets/**: Contains global assets like styles and images. + - **components/**: Contains reusable UI components, each in its own folder. + - **hooks/**: Contains custom React hooks. + - **pages/**: Contains page components, each in its own folder. + - **services/**: Contains service modules for API calls and other business logic. + - **types/**: Contains TypeScript type definitions. + - **utils/**: Contains utility functions. + - **App.tsx**: The root component of your application. + - **index.tsx**: The entry point of your application. + - **vite-env.d.ts**: TypeScript definitions for Vite-specific features. + +#### Directory Best Practices + +1. **Component-Based Structure**: Organize your code into small, reusable components. +2. **Type Safety**: Use TypeScript to define types and interfaces for your components and data structures. +3. **Custom Hooks**: Encapsulate reusable logic in custom hooks. +4. **Service Layer**: Abstract API calls and business logic into service modules. +5. **Consistent Naming**: Follow a consistent naming convention for files and directories. +6. **Environment Variables**: Use environment variables to manage configuration settings. +7. **Testing**: Write unit tests for your components, hooks, and services. + + +### Using React with Entra ID + +Integrating [React](https://reactjs.org/) applications with __Entra ID__ (formerly Azure Active Directory) allows you to secure your web applications with enterprise-grade authentication and authorization. This can be achieved using the [Microsoft Authentication Library (MSAL)](https://learn.microsoft.com/azure/active-directory/develop/msal-overview). + +To get started with Entra ID in your React application, follow these steps: + +1. **Install MSAL**: + ```sh + npm install @azure/msal-browser @azure/msal-react + ``` + +2. **Configure MSAL**: + Create a configuration file to set up your MSAL instance with your Entra ID credentials. + + ```typescript + import { PublicClientApplication, Configuration } from "@azure/msal-browser"; + + const msalConfig: Configuration = { + auth: { + clientId: "your-client-id", + authority: "//login.microsoftonline.com/your-tenant-id", + redirectUri: "//localhost:3000", + }, + }; + + export const msalInstance = new PublicClientApplication(msalConfig); + ``` + + +3. **Wrap Your Application**: + Use the `MsalProvider` to wrap your React application. + + ```typescript + import React from "react"; + import ReactDOM from "react-dom"; + import { MsalProvider } from "@azure/msal-react"; + import { msalInstance } from "./authConfig"; + import App from "./App"; + + ReactDOM.render( + + + , + document.getElementById("root") + ); + ``` + +## Managing Secrets with Environmental Variables in React Projects Using Vite + +When developing React applications, it's crucial to manage sensitive information such as API keys, database credentials, and other secrets securely. Vite provides a straightforward way to handle environmental variables. + +### Setting Up Environmental Variables + +1. **Create an `.env` File**: + In the root of your project, create a file named `.env`. This file will store your environmental variables. + + ```plaintext + VITE_API_KEY=[sample API Key] + VITE_API_URL=[sample URL] + ``` + +2. **Access Environmental Variables in Your Code**: + Vite prefixes all environmental variables with `VITE_` to ensure they are exposed to your client-side code. You can access these variables using `import.meta.env`. + + ```typescript + const apiKey: string = import.meta.env.VITE_API_KEY as string; + const apiUrl: string = import.meta.env.VITE_API_URL as string; + + fetch(`${apiUrl}/endpoint`, { + headers: { + 'Authorization': `Bearer ${apiKey}` + } + }) + .then(response => response.json()) + .then(data => console.log(data)) + .catch(error => console.error('Error fetching data:', error)); + ``` + +### Best Security Practices + +- **Do Not Commit `.env` Files**: + Ensure your `.env` file is added to `.gitignore` to prevent it from being committed to your version control system. + + ```plaintext + # .gitignore + .env + ``` + +- **Use Environment-Specific Files**: + Vite supports multiple environment files for different stages of development. For example, you can create `.env.development` and `.env.production` files to manage variables for development and production environments, respectively. + + ```plaintext + # .env.development + VITE_API_URL=[example value] + + # .env.production + VITE_API_URL=[example value] + ``` + +- **Validate Environmental Variables**: + Consider using a validation library like `zod` ( https://github.com/colinhacks/zod ) or `joi` ( joi.dev ) to validate your environmental variables at runtime, ensuring they meet the required format and constraints. + + +## Common Security Pitfalls in React Applications + +When developing React applications, it's crucial to follow best practices to safeguard your application from common security vulnerabilities. Here are some key things to avoid: + +### 1. **Do Not Store Sensitive Data in Local Storage** + +Local storage is accessible from any JavaScript code running on the same domain, making it a potential target for attackers. Avoid storing sensitive information like tokens or user data in local storage. + +**Bearer Tokens in sessionStorage and localStorage should be strictly avoided!** + +### 2. **Avoid Using `dangerouslySetInnerHTML`** + +Using `dangerouslySetInnerHTML` can expose your application to XSS attacks. Always sanitize any HTML content before rendering it. + + ```typescript + // Avoid this +
+ + // Prefer this + import DOMPurify from 'dompurify'; + + const sanitizedContent: string = DOMPurify.sanitize(userContent); +
+ ``` + +### 3. **Do Not Expose API Keys in the Frontend** + +Exposing API keys in your frontend code can lead to unauthorized access to your backend services. Use environment variables and server-side code to keep your API keys secure. + +### 4. **Do Not Ignore Security Updates** + +Regularly update your dependencies to include the latest security patches. Use tools like `npm audit` to identify and fix vulnerabilities in your project. + +### 5. **Avoid Using Untrusted Third-Party Libraries** + +Only use third-party libraries from trusted sources. Review the library's code and check for any known vulnerabilities before including it in your project. + +## Incorporating Axios for REST API Calls in React with Bearer Tokens and MSAL + +When building React applications that interact with REST APIs, [Axios](https://axios-http.com/docs/intro) is a popular library for making HTTP requests. Combined with MSAL, you can securely call APIs using Bearer tokens for authentication. + +### Setting Up Axios + +1. **Install Axios**: + ```sh + npm install axios + ``` + +2. **Create an Axios Instance**: + Configure an Axios instance to include the Bearer token in the Authorization header for all requests. + + ```typescript + import axios, { AxiosRequestConfig } from 'axios'; + import { msalInstance } from './authConfig'; + import { AuthenticationResult } from '@azure/msal-browser'; + + const apiClient = axios.create({ + baseURL: '[sample URL]', + }); + + apiClient.interceptors.request.use(async (config: AxiosRequestConfig) => { + const accounts = msalInstance.getAllAccounts(); + if (accounts.length > 0) { + const request = { + scopes: ['api://your-api-scope/.default'], + account: accounts[0], + }; + const response: AuthenticationResult = await msalInstance.acquireTokenSilent(request); + if (response && response.accessToken) { + config.headers = { + ...config.headers, + Authorization: `Bearer ${response.accessToken}`, + }; + } + } + return config; + }); + + export default apiClient; + ``` + + +### Making API Calls + +Use the configured Axios instance to make API calls within your React components. + +```typescript +import React, { useEffect, useState } from 'react'; +import apiClient from './apiClient'; + +interface DataType { + // Define the shape of your data here + id: number; + name: string; + // Add other fields as necessary +} + +const MyComponent: React.FC = () => { + const [data, setData] = useState(null); + + useEffect(() => { + const fetchData = async () => { + try { + const response = await apiClient.get('/endpoint'); + setData(response.data); + } catch (error) { + console.error('Error fetching data', error); + } + }; + + fetchData(); + }, []); + + return ( +
+ {data ?
{JSON.stringify(data, null, 2)}
: 'Loading...'} +
+ ); +}; -# npm 7.x -npm init vite@latest my-app -- --template react-ts +export default MyComponent; ```