投稿時間:2022-09-12 17:39:39 RSSフィード2022-09-12 17:00 分まとめ(43件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT @IT Test & Toolsフォーラム 最新記事一覧 Google社内ではどのようなテストツールを使っているのか https://atmarkit.itmedia.co.jp/ait/articles/2209/12/news097.html google 2022-09-12 16:30:00
IT @IT 全フォーラム 最新記事一覧 Google社内ではどのようなテストツールを使っているのか https://atmarkit.itmedia.co.jp/ait/articles/2209/12/news097.html google 2022-09-12 16:30:00
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 神奈川県の「住み続けたい街」 2位は「鎌倉市」、2年連続の1位は? https://www.itmedia.co.jp/business/articles/2209/12/news127.html itmedia 2022-09-12 16:35:00
IT ITmedia 総合記事一覧 [ITmedia PC USER] ノートPCを立ってタイピングできる昇降式スタンド https://www.itmedia.co.jp/pcuser/articles/2209/12/news135.html itmediapcuser 2022-09-12 16:33:00
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] ドミノ・ピザ、「エビマヨネーズ」を700円に 販売数量を増やす狙い https://www.itmedia.co.jp/business/articles/2209/12/news125.html itmedia 2022-09-12 16:29:00
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] Nintendo Switchソフト『スプラトゥーン3』、国内販売本数345万本突破 任天堂「発売3日後では過去最高」 https://www.itmedia.co.jp/business/articles/2209/12/news132.html ITmediaビジネスオンラインNintendoSwitchソフト『スプラトゥーン』、国内販売本数万本突破任天堂「発売日後では過去最高」任天堂は自社が手掛ける家庭用ゲーム機「NintendoSwitch」スイッチ用のソフトとして発売した『スプラトゥーン』の国内販売本数が日間で万本を突破したと発表した。 2022-09-12 16:21:00
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 箕面観光ホテル、「秋のまんぞくバイキング」をスタート 宿泊客の獲得を目指す https://www.itmedia.co.jp/business/articles/2209/09/news153.html itmedia 2022-09-12 16:15:00
TECH Techable(テッカブル) 全国の博物館・美術館が収蔵する作品が集結。オンラインミュージアムで場所に捉われない文化体験 https://techable.jp/archives/185282 能登印刷株式会社 2022-09-12 07:00:30
IT 情報システムリーダーのためのIT情報専門サイト IT Leaders 阪大とNEC、顔認証技術の倫理的・法的・社会的課題で共同研究、課題を抽出して対策を検討 | IT Leaders https://it.impress.co.jp/articles/-/23763 itleaders 2022-09-12 16:15:00
python Pythonタグが付けられた新着投稿 - Qiita Kaggle超入門 ~タイタニック号の生存予測~(データ確認編) https://qiita.com/tasuku33/items/becded4c6ec73d72ddbc kaggle 2022-09-12 16:39:49
python Pythonタグが付けられた新着投稿 - Qiita Spotify API から解析情報をとる https://qiita.com/supertower/items/1d42354dab4c152cfe3a spotifyapi 2022-09-12 16:13:56
js JavaScriptタグが付けられた新着投稿 - Qiita 151.WeakMap 152 https://qiita.com/gucho-n/items/0fcfdf48739bc0b25985 weakmap 2022-09-12 16:44:48
技術ブログ Developers.IO セキュリティグループで TCP ですべてのポートを解放していますが ping が通らないのは何故か教えてください https://dev.classmethod.jp/articles/tsnote-security-group-icmp-ping-001/ 解放 2022-09-12 07:36:16
海外TECH Ars Technica Nick Fury takes the spotlight in first trailer for Secret Invasion https://arstechnica.com/?p=1880298 marvels 2022-09-12 07:00:41
海外TECH DEV Community 💥 Introducing Skott, the new Madge! https://dev.to/antoinecoulon/introducing-skott-the-new-madge-1bfl Introducing Skott the new Madge Hello everyone hope you re doing well Today I m very pleased to share a fun project that I have been working on for several months now skott skott is a tool that generates a graph of dependencies from your Node js projects including both ES and CommonJS modules and helps you discover circular dependencies cost imports file sizes unused imports exports work in progress and many more Node js builtin and or npm third party dependencies can also be configured to be added in the graph The main goal is to reproduce the architecture of your Node js application at the file level Installation and use npm install skottskott provides an API to traverse the project graph deeply search for circular dependencies find parents or children for a given set of nodes etc Here is a quick overview of the API import skott from skott const getStructure findCircularDependencies findParentsOf findLeaves await skott The entrypoint of the project Must be either a CommonJS or ES module For now TypeScript files are not supported as entrypoints entrypoint dist index js Define the max depth of for circular dependencies search This can be useful for performance purposes This defaults to POSITIVE INFINITY circularMaxDepth This defines whether the base directory of the entrypoint must be included in all the relatives file paths For the specified dist index js above it would consider the root path to be consequently dist would never appear in any file paths includeBaseDir false skott can also be used through the CLI Here is a quick preview of the graph generated for the fastify library using the CLI We can also decide to track more dependencies for example the npm third party dependencies by providing the trackThirdPartyDependencies option Node js builtin dependencies can also be tracked by providing the trackBuiltinDependencies option File tree displayDifferent modes of display are available from the CLI including file tree which which reconstructs a directory of files from the graph which is far more concise Circular dependenciesskott also helps finding out circular dependencies very efficiently in the project you can even provide a max depth search to avoid deep searches that could be costly Skott is fastWe can easily compare skott with madge because skott already covers most of the features madge exposes minus the image generation I did some benchmarks about the computing time required to build a set of graphs from popular libraries for both skott and madge and here are the results Knex js O files knex js A SQL query builder that is flexible portable and fun to use using skott takes msusing madge takes msFor building the entire graph of knex js with even more metadata skott is times faster Fastify js files fastify js is a fast and low overhead web framework for Node jsusing skott takes msusing madge takes msIn this case skott is times faster than madge Stay tunedMany more features will be implemented skott does not yet have a major version released to help you easily discover and demystify what s going on under the hood of your Node js project I m also thinking about developing a Web Application that will help you visualize graphs and every metadata related to each file number of imports file size unused imports etc Sharing journey of building an open source libraryI ll also start a series about the journey of building skott which notably includes What is a program parser and how to use itHow to interpret an Abstract Syntax TreeHow to make all of that fully testable by using dependency injection and Test Driven Development Don t hesitate to bring stars ️ issues feedbacks directly on GitHub here as it will allow me to drive the project where it will bring the most value for each developer Thanks for reading this far wish everyone a wonderful day ️ 2022-09-12 07:49:34
海外TECH DEV Community How To Build NFT Marketplace With Aid of An NFT Marketplace Creator https://dev.to/puneetverma3210/how-to-build-nft-marketplace-with-aid-of-an-nft-marketplace-creator-4n51 How To Build NFT Marketplace With Aid of An NFT Marketplace Creator What Is An Non Fungible Token Non Fungible tokens are virtual tokens just like cryptocurrencies Cryptocurrencies are basically some piece of code that is used in a special manner to build virtual currencies Similarly Non Fungible tokens are also some pieces of code that represents real life things like painting game songs etc These are distinctive and non transferable digital records These can be simply developed and sold on a specific marketplace platform This platform is called the NFT Marketplace platform It is open to everyone anyone can simply come to this platform to create buy and sell NFTs It can be built with aid of NFT Marketplace development services What Exactly Is An NFT Marketplace If you want to sell or buy something you will have to find a seller A place with various e shoppers is called a Marketplace Similarly an online or virtual marketplace wherein you can find various NFT buyers and sellers is called an NFT Marketplace There are various marketplaces in real life wherein people can find various sellers Similarly there could be various NFT Marketplaces too There are some business minded people who want to start their businesses in NFT So they get in touch with NFT Marketplace creators like Bagisto It is a well known NFT Marketplace creator that has served various local and international clients Its hands on experienced and the team of highly skilled amp certified developers is the main attraction of this NFT Marketplace builder This builder assures the hassle free minting and trading of NFTs An NFT Marketplace can be built with the help of blockchain technology This technology aids to maintain transparency amp immutability in the trading process How To Develop Your Own NFT MarketplacePHP NFT Marketplace Script can help to build an NFT Marketplace NFT Marketplace development is too easy you just need to follow a few steps Firstly you need a business model and then follow a very easy process which is written below Understand and Select Your NicheUse Technology For Your NFT MarketplaceDecide The UI UX Design For Your NFTValidate And Release NFT MarketplaceFind Estimated Price To Launch NFT Marketplace 2022-09-12 07:35:58
海外TECH DEV Community API monetization using an API Management and a billing provider https://dev.to/apisix/api-monetization-using-an-api-management-and-a-billing-provider-863 API monetization using an API Management and a billing provider API MonetizationAs an owner of API you develop some code and deploy it to a server that server might have a bunch of HTTP HTTPs endpoints that do something useful Maybe like retrieving data about all current discounts and voucher information from different markets in your city And other developers want to use this data but they do not want to implement the same solution on their own So they reach out to you for permission to make requests to your server Using APIs is an ideal way to monetize your services An API lets you reach customers through multiple channels and allows third party applications or developers to consume your data API monetization is a way that businesses can use APIs to convert usages of the data into money When it comes to making money from your APIs there are multiple ways Most often you think about how to get started with the right tools and how to set up billing for your APIs This blog post gives you an idea of building your technology stack with an API Gateway and a payment provider that can help you run quickly and securely your API monetization system which simply provides flexibility for your customers Here is a quick overview of what we covered Monetization options Two common ways to monetize APIs Simple API monetization stack components an API Management and a billing provider How API Management and a payment platform work together How to apply rate limiting policies How Apache APISIX can be useful to monitor and limit API usage API monetization modelsThere are several pricing approaches you can take for monetization When you are developing API monetization strategies you should always consider that you deliver high quality consistent value to your API users As the API Provider you talk to your current API users to identify problems your service is solving and offer pricing models according to the target customer For example if customers use one specific feature of your API more than others you could spin that feature off into its own product with its own pricing plan Some API billing models for monetization include Freemium Pay as you go Subscription Pay per transaction Revenue share Pay for ad free content Paid partner In the freemium model Developers have access to a basic API for free up to a specific threshold and transition to pay per use in a tiered pricing model when they exceed that limit This model is quite often used to explore API use cases test your APIs or make quick a proof of concept You can learn more about other models in depth here Two common ways to monetize APIsLet s take a look closely at the most common ways to directly monetize your APIs like the Subscription billing model where you charge your customers a flat monthly fee to access your APIs and Metered billing model where you charge your customers based on the number of API calls they make Subscription Billing ModelIn this model API Consumer pays for a set of numbers of calls per month For example a consumer pays to access up to API calls per month Whether they make API calls or API calls the consumer is charged each month Metered Billing ModelWith a Metered Billing model API Consumers can make as many calls as they want per month and you only charge the consumer a fee for each API call they make If the customer makes API calls at per call then the bill at the end of the month would be Calculating billsCalculating bills in subscription based pricing model is very straightforward because you don t need to count how many API calls were made Instead you charge each user a flat monthly fee However calculating bills for metered users might be a little bit challenging since we need to have custom code in your API service that not only tracks API usage but it should be also capable of applying rate limiting policies to the APIs depending on users accessing your APIs In this case we might need to consider a suitable API monetization stack with existing solutions to build a solid foundation for your API monetization that reduces the time and investment required to build your own service to measure API usage Two simple API monetization stack componentsWe can choose the combination of two elements for our API monetization stack that most modern businesses are using nowadays API Management like an API Gateway and a billing provider Let s break down each component and understand the role of each in API monetization API ManagementAPI Management service itself offers two helpful features such as API Gateway and API Analytics API analytics feature can be used for tracking API usage because the analytics is able to collect API consumption metrics around every API call made by each of your API consumers This usage data can be used to bill each consumer and send an invoice to collect monthly payments For example Apache APISIX can also integrate with a variety of observability platforms like Prometheus OpenTelemetry Apache Skywalking and etc by using its connector plugins to further analyze API performance and gain complete visibility  API Gateway can help with the challenges that you meet with implementing cross cutting concerns for APIs As an API Gateway acts as a central proxy to route all incoming requests from your clients to intended destinations backend services it can make securing and managing your APIs much easier Most gateways support a wide variety of authorization and authentication protocols to control API access caching mechanisms for API responses or support for rate limiting and exposing quotas with API usage details  There are many popular open source projects available like Apache APISIX or alternative enterprise SaaS solutions such as Azure API Management API Cloud in a public cloud You can investigate the pros and cons of each to choose the more suitable one for your needs Apply rate limit policiesResources cost money We can protect an API by adding a rate limit policy with Apache APISIX as it is a basic step toward API Monetization Apache APISIX allows you to set throttling limits per each API consumer and quotas to your APIs and allows you to control third party usage of your API by ensuring you are able to monetize your API APISIX uses its limit count rate limiting plugin API rate limiting plugin can prevent an API not only from being overwhelmed or from possible malicious attacks but also it can enforce a limit on the number of data clients can consume Later you can charge API consumers by the quantity of data used the number of requests With the help of APISIX rate limiting plugin you can also configure the different rate limits for authenticated and unauthenticated requests It also defines the limit quota in the response headers to track the maximum number of requests you are permitted to make or the number of requests remaining in the current rate limit window Refer to the documentation to understand Consumer concept and learn the different ways to set up rate limiting with Apache APISIX A billing providerNext for your API monetization stack you need a rd party recurring billing solution such as Stripe Recurly Hypercurrent and many more But again we do not recommend any particular payment service in this post and leave the choice of which payment provider to use up to you The billing provider obviously needs to receive usage charges for each customer issue an invoice and support multiple billing models currencies and payment methods How API Management and a billing platform work togetherTo make these two API monetization components work well together you need to integrate API Management and billing software For instance Apache APISIX tracks API usage in real time saves consumption details and exposes a dedicated endpoint with an API usage report On the other hand the billing provider enables you to send a monthly invoice to each of your consumer s API usage You ll also want to be aware of what it takes to integrate the billing provider with your current solution by considering the fact that different providers have different ways to integrate mainly through API communication We will describe the integration process with Apache APISIX with a step by step tutorial in our next post in this series   ConclusionAs we went through the post there is an effortless way to monetize your API that consists of two components an API Management service and a billing provider  To get started identify your API monetization model as the first step Next manage your APIs with an API Gateway and set throttling limits and quotas to your APIs Then choose a proper payment provider to deal with processing payment transactions issuing invoices and managing subscriptions On a later stage apply API analytics to your system so you can monitor API usage and scale it as needed You can review the analytics reports regularly to understand how your monetization strategy is being adopted by API consumers Related resources➔What is API monetization ➔Best SaaS Subscription Billing Solution ➔API Monetization Models Recommended content ➔Watch Video Tutorial Getting Started with Apache APISIX APIs security with Apache APISIX ➔Read the blog posts Overview of Apache APISIX API Gateway Plugins API Observability with Apache APISIX Plugins Community️Join the Apache APISIX Community Follow us on TwitterFind us on SlackMail to us with your questions 2022-09-12 07:27:14
海外TECH DEV Community How Much Does It Cost to Build WebRTC Application? https://dev.to/quokkalabs/how-much-does-it-cost-to-build-webrtc-application-3d7k How Much Does It Cost to Build WebRTC Application Are you looking to build a WebRTC application If so you may be questioning how much it will cost A few factors will affect your project s cost including the size and complexity of your project the platform you re building for and the developers firm you re working with The use of WebRTC for voice and video eases the cost determination difficulties There are no hidden or extra associated costs It will be easier to determine the price if you migrate from your proprietary system to WebRTC Here Web application development services come in handy too The five areas of cost estimation for a WebRTC project are ImplementationTrainingMaintenanceLicensesTransactionsSubscriptionBandwidthThe following explanation assumes that a typical RTC project has been developed with a proprietary system that initially requires dedicated servers The WebRTC based system fully utilizes a third party WebRTC service provider So let s get started with Implementation Implementation Cost and TimeFinding an estimation of the time and cost of the project that moves from design to production is an art of science To speed up project execution and cut costs compared to proprietary alternatives WebRTC offers significant advantages First any browser that supports WebRTC directly accesses it through its APIs Testing time is reduced to Make sure it works the same on Chrome Firefox and Microsoft Edge browsers since no third party code or plug ins need to be installed While setting up proprietary solutions can take hours or even days setting up a developer s account for a WebRTC provider only takes five minutes WebRTC web application development is way faster because of HTML capabilities Because of HTML any developer can add video and voice in minutes using code examples The time it consumes is typically longer because of the dedicated solution but the output is better You can reach out to a web application development provider to finalize and finetune your plan from design to deployment So all businesses can take advantage of the WebRTC app WebRTC development can take place in a free sandbox account without cost until the production stage Here another cost saving is that HTML developers can work on it and save expenses Training Cost and TimeImplementing from a proprietary to WebRTC solution is not minor and quick But WebRTC development needs training of staff of minimum to three days It comes free if it s a package deal WebRTC is easy to learn in days of trial by an HTML developer and can be quickly learned by course study Due to the variety of conferencing choices available for training and understanding more about how it is being used this may marginally favor WebRTC For events promoting their products vendors typically charge extra Maintenance CostMaintenance costs depend on how complex your WebRTC app is and which services it is providing So it all depends on the money you spend on it The faster responses you will get the more money you spend on it and the cycle starts going on In short faster responses depend on how much money the service provider spends If you are confused and can t find a good one head to this Web application development services Licenses CostWebRTC is open source so there s no charge but hardware costs can add But it s all about cloud solutions there will be fewer costs related to hardware No dedicated hardware is required here so WebRTC works better and wins the race among other solutions Transaction CostAlthough a proprietary on site solution won t usually have a cost per transaction getting there requires paying a lot upfront Costs for WebRTC service providers are a little more complex with all fees coming under operating expenses By using the WebAPI API call to their server service providers can charge a fixed rate per user or usage with volume lowering the cost per use Depending on the services included or included a per user per month pricing may range from to For a WebRTC API call per use fees can range from fractions of a penny to several multiples of tenths of a cent in volume Other pillars that affect costs includeSubscriptionsBandwidthLet s take a quick look at it Subscriptions TypeSubscription mainly focuses on minutes The most frequent task performed here is counting devices or subscriptions The publish subscribe approach is typically not reliable for most WebRTC PaaS based services Sessions are capable of publishing media streams and enabling device based media stream subscriptions It is the best strategy when painting a clear picture of a complex situation The most cost effective WebRTC PaaS option is one that charges for subscribed minutes rather than for the minutes of each device in smaller group sizes BandwidthWhen customers perceive minute pricing as transporting them back to the early days of telecom a red flag is triggered It was envisaged that costs would depend more on consumption once other services were developed or deployed rather than being restricted to a minute by minute method With all of these companies are speculating on adopting a very different but excellent strategy This strategy which we refer to as pricing per bandwidth is one that is frequently used in IaaS Because cloud services are paid for by the vendor using the bandwidth sent on devices and browsers it would therefore be subscribed bandwidth The price is not determined by the amount of bandwidth used on cloud servers Final Cost EstimationGenerally it costs around and for a WebRTC project Of course your project may be on the lower or higher end of that scale depending on the above factors Suppose you re looking for an exact project estimate Speaking with a development team about your specific needs is far better They will be able to give you a more accurate estimate based on your project requirements You can reach out to web application development services to discuss your idea ConclusionIn this blog we have seen various factors that affect the WebRTC app cost by web application development service WebRTC app development is more cost effective than a proprietary solution A meager cost for installation maintenance and licensing is free Another cost only depends on which cost model is used and the frequency of use Suppose you need an efficient cost model and a finetuned solution that doesn t go over budget for your business you can reach us at web application development services 2022-09-12 07:25:58
海外TECH DEV Community Build Authentication Using Firebase | React | Express https://dev.to/earthcomfy/build-authentication-using-firebase-react-express-28ig Build Authentication Using Firebase React ExpressHi everyone in this tutorial we are going to fire up an authentication system using React Firebase and Express We will also use Tailwind to create the user interface Table of ContentsIntroductionReact and Tailwind Set UpReact RouterRegister and Login ComponentsFirebase Set UpFirebase and React IntegrationReact ContextError HandlingProfileLogoutEnable Dark ModeNavigationPrivate RouteExpress ServerExpress BoilerplateEnabling CorsUsing Environment VariablesConnect with ReactSending Firebase Token to ExpressCreating the MiddlewareFinal Thoughts Introduction To set up a registration authentication system we will leverage Firebase a Backend as a Service Baas What s a BaaS Cloud computing has transformed the way we use technology The BaaS cloud service model allows developers to focus on the frontend of an application by abstracting away all the stuff that goes behind it Through BaaS developers outsource pre written software for different activities such as user authentication database management cloud storage hosting push notifications and so on We are going to use the user authentication service provided by Firebase for this project Here is the workflow React will send a request to register and login a user to Firebase Firebase will give a token to ReactReact will use that token to send subsequent requests to an Express server The Express server will verify the token using the Firebase admin SDK and sends a response back to React Quick Note Technically you don t need Express for this if you aren t going to use a backend for your project However in our case we need an Express server to later create the chat API endpoints and connect with MongoDB Also if you encounter any issues throughout the tutorial you can check out the code in the GitHub repository React and Tailwind Set Up Let s create a React application first Type in the following to create a React app npx create react app frontendRemove git since we won t use it inside the frontend app If you are on Linux you can remove it by running this cd frontendrm rf gitAlright we are going to use Tailwind CSS to create the components so let s install it Make sure you are inside the frontend folder open up your terminal and install Tailwind CSS Installs tailwindcss and its dependenciesnpm install D tailwindcss postcss autoprefixer Generates tailwind config js and postcss config js filesnpx tailwindcss init pOpen tailwind config js and configure your template paths type import tailwindcss Config module exports content src js jsx ts tsx theme extend plugins Open index css remove the content and add the following Tailwind directives Check this out to learn more about these Tailwind specific at rules tailwind base tailwind components tailwind utilities Now let s delete files we won t be using The final structure should look something like this Your index js file should look like this import React from react import ReactDOM from react dom client import index css import App from App const root ReactDOM createRoot document getElementById root root render lt React StrictMode gt lt App gt lt React StrictMode gt And finally to make sure everything is set up correctly add the following to App js and start the project App jsfunction App return lt div gt lt h className text xl font bold underline gt Hello world lt h gt lt div gt export default App Start the project npm run startPerfect now inside the src folder create another folder named components Then inside components create a folder named accounts We will put user auth related components inside it Inside accounts create files named Register js and Login jsFor now put a boilerplate like the following If you are on VSCode you can generate this by using the rfc shortcut Register jsimport React from react export default function Register return lt div gt Register lt div gt Login jsimport React from react export default function Login return lt div gt Login lt div gt React Router We will be using React router V for routing between different pages Let s go ahead and install it npm i react router domOpen App js and create the path for login and register App jsimport BrowserRouter as Router Routes Route from react router dom import Register from components accounts Register import Login from components accounts Login function App return lt Router gt lt Routes gt lt Route exact path register element lt Register gt gt lt Route exact path login element lt Login gt gt lt Routes gt lt Router gt export default App Go to your browser and test the routes http localhost login and http localhost register Register and Login Components Up until this point we have been doing basic configuration Let s now get to creating the UI for account registration and login Register jsimport Link from react router dom export default function Register return lt div className min h full flex items center justify center py px sm px lg px gt lt div className max w md w full space y gt lt div gt lt h className mt text xl text center tracking tight font light dark text white gt Register your account lt h gt lt div gt lt form className mt space y gt lt div className rounded md shadow sm space y px gt lt div gt lt input id email address name email type email autoComplete email required className appearance none rounded none relative block w full px py placeholder gray rounded t md bg gray border border gray text gray text sm focus outline none focus ring blue focus border blue dark bg gray dark border gray dark placeholder gray dark text white dark focus ring blue dark focus border blue focus z sm text sm placeholder Email address gt lt div gt lt div gt lt input id password name password type password autoComplete current password required className appearance none rounded none relative block w full px py placeholder gray rounded t md bg gray border border gray text gray text sm focus outline none focus ring blue focus border blue dark bg gray dark border gray dark placeholder gray dark text white dark focus ring blue dark focus border blue focus z sm text sm placeholder Password gt lt div gt lt div gt lt input id confirmPassword name confirmPassword type password autoComplete current password required className appearance none rounded none relative block w full px py placeholder gray rounded t md bg gray border border gray text gray text sm focus outline none focus ring blue focus border blue dark bg gray dark border gray dark placeholder gray dark text white dark focus ring blue dark focus border blue focus z sm text sm placeholder Password gt lt div gt lt div gt lt div gt lt button type submit className w full flex justify center py px border border transparent text sm font medium rounded md text white bg sky hover bg sky gt Register lt button gt lt div gt lt div className flex items center justify between gt lt div className text sm gt lt Link to login className text blue hover underline dark text blue gt Already have an account Login lt Link gt lt div gt lt div gt lt form gt lt div gt lt div gt We have fields One for Email the other two for password and password confirmation respectively And for Login js we have fields Email and password Login jsimport Link from react router dom export default function Login return lt div className min h full flex items center justify center py px sm px lg px gt lt div className max w md w full space y gt lt div gt lt h className mt text xl text center tracking tight font light dark text white gt Login to your account lt h gt lt div gt lt form className mt space y gt lt div className rounded md shadow sm space y px gt lt div gt lt input id email address name email type email autoComplete email required className appearance none rounded none relative block w full px py placeholder gray rounded t md bg gray border border gray text gray text sm focus outline none focus ring blue focus border blue dark bg gray dark border gray dark placeholder gray dark text white dark focus ring blue dark focus border blue focus z sm text sm placeholder Email address gt lt div gt lt div gt lt input id password name password type password autoComplete current password required className appearance none rounded none relative block w full px py placeholder gray rounded t md bg gray border border gray text gray text sm focus outline none focus ring blue focus border blue dark bg gray dark border gray dark placeholder gray dark text white dark focus ring blue dark focus border blue focus z sm text sm placeholder Password gt lt div gt lt div gt lt div gt lt button type submit className w full flex justify center py px border border transparent text sm font medium rounded md text white bg sky hover bg sky gt Login lt button gt lt div gt lt div className flex items center justify between gt lt div className text sm gt lt Link to register className text blue hover underline dark text blue gt Don t have an account Register lt Link gt lt div gt lt div gt lt form gt lt div gt lt div gt Don t worry about the classes of the elements that are prefixed with dark We will talk about them later when we enable dark mode Let s now use the useState hook to store the form data Inside Register js import useState at the top and add the following states import useState from react const email setEmail useState const password setPassword useState const confirmPassword setConfirmPassword useState Then add an onChange event listener to the input fields as follows onChange e gt setEmail e target value onChange e gt setPassword e target value onChange e gt setConfirmPassword e target value We now need a function that will handle the form submission async function handleFormSubmit e e preventDefault Here We will get form values and invoke a function that will register the user Add the function as an onSubmit event listener to the form onSubmit handleFormSubmit Do the same thing for Login js The only difference is that we don t have a confirm password input field The rest is the same Now that our forms are ready let s move our attention to Firebase Firebase Set Up If it s your first time using Firebase follow the following steps to create a project Otherwise you can move to the next section We first need to create a Firebase project using the Firebase console so Log in and then click Create a project Give any name you like for the project and click Continue You will then be prompted to enable Google Analytics for your project optional We don t need that Once you have completed the steps you will be presented with a Dashboard Click on Authentication from the navigation panel and go to the Sign in Method tab Enable Email Password method since that s what we are going to use Firebase and React Integration For React to communicate with Firebase services we need to install the firebase package npm i firebaseAfter you have created a new project in Firebase you need to create an application Go to your Firebase Console dashboard click on Project Settings and select this icon lt gt to add Firebase to your web app Doing so will give you config data Create a env file inside the root directory of your project and store all these config data in it envREACT APP FIREBASE API KEY REACT APP FIREBASE AUTH DOMAIN REACT APP FIREBASE PROJECT ID REACT APP FIREBASE STORAGE BUCKET REACT APP FIREBASE MESSAGING SENDER ID REACT APP FIREBASE APP ID When setting up environment variables you should prefix them with REACT APP In addition make sure to put the env file in your root folder Finally restart your server for the changes to take place Inside the src folder create a folder called config and inside it create a file called firebase js This is where we will set up Firebase firebase jsimport initializeApp from firebase app import getAuth from firebase auth const firebaseConfig apiKey process env REACT APP FIREBASE API KEY authDomain process env REACT APP FIREBASE AUTH DOMAIN projectId process env REACT APP FIREBASE PROJECT ID storageBucket process env REACT APP FIREBASE STORAGE BUCKET messagingSenderId process env REACT APP FIREBASE MESSAGING SENDER ID appId process env REACT APP FIREBASE APP ID const app initializeApp firebaseConfig gives us an auth instanceconst auth getAuth app in order to use this auth instance elsewhereexport default auth Now that we have Firebase setup we can start doing authentication React Context We are going to use React context to set up the authentication because we want to access the current user everywhere in our app If you aren t familiar with React context don t worry We are going to walk through it together React context allows us to share data state across our components more easily This is great when you are passing data that can be used in any component of your application Inside the src folder create a folder named contexts and inside it create a file named AuthContext js and put the following to set up context AuthContext jsimport createContext useContext from react const AuthContext createContext export function useAuth return useContext AuthContext export function AuthProvider children const value return lt AuthContext Provider value value gt children lt AuthContext Provider gt What is going on Well let me explainconst AuthContext createContext will return a Consumer and a Provider component Provider provides state to its children It takes in the value prop and passes it down to its children components that might need to access them The Consumer consumes and uses the state passed down to it by the Provider In the above case the component that will wrap the Provider is AuthProvider We also exported it so that we can use it elsewhere The custom useAuth hook will allow us to consume context in our application by returning a useContext instance of AuthContextThat is the basic setup for context Let s now add Firebase functions to register login and find the current user First import createUserWithEmailAndPassword and signInWithEmailAndPassword that Firebase provides for user registration and login Also import auth from our earlier Firebase configuration AuthContext jsimport createUserWithEmailAndPassword signInWithEmailAndPassword from firebase auth import auth from config firebase Users can create a new account by passing their email address and password The functions return a Promise and we will consume that inside the register and login components function register email password If the new account was created the user is signed in automatically return createUserWithEmailAndPassword auth email password function login email password return signInWithEmailAndPassword auth email password Alright but how can we get the signed in user details We can set an observer on the auth object Before that however let s first create a state that will store the current user and pass it down in the value props import useState from react const currentUser setCurrentUser useState const value currentUser We can now set the onAuthStateChanged observer on the auth object This will notify us when the user is signed in and update the state import useEffect from react const loading setLoading useState true useEffect gt const unsubscribe auth onAuthStateChanged user gt setCurrentUser user setLoading false return unsubscribe return lt AuthContext Provider value value gt loading amp amp children lt AuthContext Provider gt The observer i e onAuthStateChanged is put inside a useEffect because we only want to render it once i e when the component mounts When the component un mounts we unsubscribe from the event The loading state is initially set to true When Firebase finishes its job and updates the user we set it to false This will prevent the children components from rendering while the action is taking place The final code for AuthContext js should look like this AuthContext jsimport createContext useContext useState useEffect from react import createUserWithEmailAndPassword signInWithEmailAndPassword from firebase auth import auth from config firebase const AuthContext createContext export function useAuth return useContext AuthContext export function AuthProvider children const currentUser setCurrentUser useState const loading setLoading useState true function register email password return createUserWithEmailAndPassword auth email password function login email password return signInWithEmailAndPassword auth email password useEffect gt const unsubscribe auth onAuthStateChanged user gt setCurrentUser user setLoading false return unsubscribe const value currentUser login register return lt AuthContext Provider value value gt loading amp amp children lt AuthContext Provider gt Let s now wrap our components inside of the AuthProvider so that we have access to the context App jsimport BrowserRouter as Router Routes Route from react router dom import AuthProvider from contexts AuthContext import thisimport Register from components accounts Register import Login from components accounts Login function App return lt AuthProvider gt Wrap everything inside this provider lt Router gt lt Routes gt lt Route exact path register element lt Register gt gt lt Route exact path login element lt Login gt gt lt Routes gt lt Router gt lt AuthProvider gt export default App Now to use the register and currentUser context head over to Register js and import the useAuth hook Register jsimport useAuth from contexts AuthContext Then import useEffect and useNavigate and add the following import useEffect from react import useNavigate from react router dom const navigate useNavigate const currentUser register useAuth const loading setLoading useState false useEffect gt if currentUser navigate currentUser navigate const navigate useNavigate React router hook that returns a function to navigate programmatically const currentUser register useAuth gets the currentUser and register contexts since those are what we will be using The loading state will be used to disable the button when the registration action is executing The useEffect hook is in place to prevent users from accessing the registration page while they are authenticated It will redirect them to the home page if they try to do so Then inside the handleFormSubmit function we created earlier we are going to handle the registration logic async function handleFormSubmit e e preventDefault if password confirmPassword return alert Passwords do not match try setLoading true await register email password navigate profile catch e alert Failed to register setLoading false First if the passwords don t match we exit out of the function by alerting the error For now we are not managing the errors Later however we will handle them using a state The register function returns a promise so we are using the await keyword to wait for the call to be settled And we are using the try…catch block for error handling If the call is successful the user will be redirected to the profile page we haven t created it yet However the flow will be sent to the catch block if it fails To disable the submit button when the action is executing add disabled loading to the submit Button Cool let s test what we have so far Start your server and go to http localhost register and fill in the form with passwords that don t match You should get the following alert Now fill in the correct credentials and you should be redirected to http localhost profile However since we haven t created this route yet nothing will be displayed Do the same thing for the Login js component You only need to change the register call to login and remove the password confirmation check Error Handling We want to use a single component that will handle and display errors if there are any For this let s use context Go to AuthContext js and create this state const error setError useState Add it to the value props const value error setError Inside components create a folder named layouts And inside it create a file called ErrorMessage js We will use this component to display error messages from anywhere in our app First let s install herocions to use the X icon in our alert npm i heroicons react vThen inside ErrorMessage js ErrorMessage jsimport XCircleIcon from heroicons react solid import useAuth from contexts AuthContext export default function ErrorMessage const error setError useAuth return error amp amp lt div className flex justify center gt lt div className rounded md max w md w full bg red p mt gt lt div className flex gt lt div className flex shrink gt lt XCircleIcon onClick gt setError className h w text red aria hidden true gt lt div gt lt div className ml gt lt h className text sm font medium text red gt Error error lt h gt lt div gt lt div gt lt div gt lt div gt The above snippet checks if there is an error and displays it When the X icon is clicked it will set the error to an empty string Then render this component inside App js at the top import ErrorMessage from components layouts ErrorMessage add this import lt AuthProvider gt lt Router gt lt ErrorMessage gt add this lt Routes gt lt Route exact path register element lt Register gt gt lt Route exact path login element lt Login gt gt lt Routes gt lt Router gt lt AuthProvider gt Now let s update Register js to set the errors accordingly const currentUser register setError useAuth Get setError as wellasync function handleFormSubmit e e preventDefault if password confirmPassword return setError Passwords do not match Replace the alert with this try setError Remove error when trying to register setLoading true await register email password navigate profile catch e setError Failed to register Replace the alert with this setLoading false Do the same thing for Login js and test it Before testing it though make sure to comment out the useEffect hook that checks if there is a current user so that it won t redirect you to the home page You should get something like this Profile Now that we have registration and login set up let s create a route to set a name and avatar for users The Firebase user object has basic properties such as displayName photoURL phoneNumber etc You can check this by logging the currentUser object on the console We are going to update the user s profile by using the updateProfile function from Firebase Open AuthContext js and import this function import updateProfile from firebase auth Add the following function alongside register and loginfunction updateUserProfile user profile return updateProfile user profile The updateProfile function takes a user and any user information we need to update Add updateUserProfile in value props const value updateUserProfile We are going to update the display name and photo of the user To generate cool avatars we are going to use this API DiceBear uses the following URL as a source to generate images sprites seed svgYou can replace  sprites with male  female  human  identicon  initials  bottts  avataaars  jdenticon  gridyor micah The value of  seed can be anything you like but don t use any sensitive or personal data here Inside the src folder create a folder called utils And inside it create a file called GenerateAvatar js GenerateAvatar jsconst generateDiceBearAvataaars seed gt seed svg const generateDiceBearBottts seed gt seed svg const generateDiceBearGridy seed gt seed svg export const generateAvatar gt const data for let i i lt i const res generateDiceBearAvataaars Math random data push res for let i i lt i const res generateDiceBearBottts Math random data push res for let i i lt i const res generateDiceBearGridy Math random data push res return data The above function generates random avatars and returns the array We have exported the function so that we can use it elsewhere Now create a file called Profile js inside accounts Most of the things in this file are going to be similar to Register js and Login js Profile jsimport generateAvatar from utils GenerateAvatar const avatars setAvatars useState useEffect gt const fetchData gt const res generateAvatar setAvatars res fetchData This will generate avatars using the utility function we created earlier and set them to the avatars state when the component mounts We will also have the following state to track the selected avatar const selectedAvatar setSelectedAvatar useState This is what Profile js looks like now Profile jsimport useState useEffect from react import useNavigate from react router dom import useAuth from contexts AuthContext import generateAvatar from utils GenerateAvatar function classNames classes return classes filter Boolean join export default function Profile const navigate useNavigate const username setUsername useState const avatars setAvatars useState const selectedAvatar setSelectedAvatar useState const loading setLoading useState false const currentUser updateUserProfile setError useAuth useEffect gt const fetchData gt const res generateAvatar setAvatars res fetchData const handleFormSubmit async e gt e preventDefault if selectedAvatar undefined return setError Please select an avatar try setError setLoading true const user currentUser const profile displayName username photoURL avatars selectedAvatar await updateUserProfile user profile navigate catch e setError Failed to update profile setLoading false return lt div className min h full flex items center justify center py px sm px lg px gt lt div className max w md w full space y gt lt div className text center gt lt h className mt text xl text center tracking tight font light dark text white gt Pick an avatar lt h gt lt div gt lt form className space y onSubmit handleFormSubmit gt lt div className flex flex wrap m md m gt avatars map avatar index gt lt div key index className flex flex wrap w gt lt div className w full p md p gt lt img alt gallery className classNames index selectedAvatar border border blue dark border blue cursor pointer hover border hover border blue block object cover object center w h rounded full src avatar onClick gt setSelectedAvatar index gt lt div gt lt div gt lt div gt lt div className rounded md shadow sm space y px gt lt input id username name username type text autoComplete username required className appearance none rounded none relative block w full px py placeholder gray rounded t md bg gray border border gray text gray text sm focus outline none focus ring blue focus border blue dark bg gray dark border gray dark placeholder gray dark text white dark focus ring blue dark focus border blue focus z sm text sm placeholder Enter a Display Name defaultValue currentUser displayName amp amp currentUser displayName onChange e gt setUsername e target value gt lt div gt lt div gt lt button type submit disabled loading className w full py px border border transparent text sm font medium rounded md text white bg blue hover bg blue focus ring focus outline none focus ring blue dark bg blue dark hover bg blue dark focus ring blue gt Update Profile lt button gt lt div gt lt form gt lt div gt lt div gt Now let s create the route in App jsimport Profile from components accounts Profile Add this to the imports list lt Route exact path profile element lt Profile gt gt Add this routeFinally go to http localhost profile and check if everything is working You will get something like this When you update the profile it will redirect you to a blank page don t worry we haven t created a home page yet Logout First let s add the Firebase function that will allow us to log out users Inside your AuthContext js add the followingimport signOut from firebase auth Add this importfunction logout return signOut auth Simple as that Then create a file called Logout js inside the accounts folder We are going to create a modal that will ask for the user s confirmation to log out and fires the logout function We are going to use the Dialog and Transition components from Headless UI so let s install it firstnpm i headlessui react Logout jsimport Fragment useRef from react import useNavigate from react router dom import Dialog Transition from headlessui react import ExclamationIcon from heroicons react outline import useAuth from contexts AuthContext export default function Logout modal setModal const cancelButtonRef useRef null const navigate useNavigate const logout setError useAuth async function handleLogout try setError await logout setModal false navigate login catch setError Failed to logout return lt Transition Root show modal as Fragment gt lt Dialog as div className fixed z inset overflow y auto initialFocus cancelButtonRef onClose setModal gt lt div className flex items end justify center min h screen pt px pb text center sm block sm p gt lt Transition Child as Fragment enter ease out duration enterFrom opacity enterTo opacity leave ease in duration leaveFrom opacity leaveTo opacity gt lt Dialog Overlay className fixed inset bg gray bg opacity transition opacity gt lt Transition Child gt This element is to trick the browser into centering the modal contents lt span className hidden sm inline block sm align middle sm h screen aria hidden true gt amp lt span gt lt Transition Child as Fragment enter ease out duration enterFrom opacity translate y sm translate y sm scale enterTo opacity translate y sm scale leave ease in duration leaveFrom opacity translate y sm scale leaveTo opacity translate y sm translate y sm scale gt lt div className inline block align bottom bg white rounded lg text left overflow hidden shadow xl transform transition all sm my sm align middle sm max w lg sm w full gt lt div className bg white dark bg gray px pt pb sm p sm pb gt lt div className sm flex sm items start gt lt div className mx auto flex shrink flex items center justify center h w rounded full bg red dark bg gray sm mx sm h sm w gt lt ExclamationIcon className h w text red aria hidden true gt lt div gt lt div className mt text center sm mt sm ml sm text left gt lt Dialog Title as h className text lg leading font medium text gray dark text gray gt Logging out lt Dialog Title gt lt div className mt gt lt p className text sm text gray dark text gray gt Are you sure you want to log out lt p gt lt div gt lt div gt lt div gt lt div gt lt div className bg gray dark bg gray px py sm px sm flex sm flex row reverse gt lt button type button className w full inline flex justify center rounded md border border transparent shadow sm px py bg red text base font medium text white hover bg red focus outline none focus ring focus ring offset focus ring red sm ml sm w auto sm text sm onClick handleLogout gt Logout lt button gt lt button type button className mt w full inline flex justify center shadow sm px py sm mt sm ml sm w auto sm text sm rounded md border border gray bg white text gray text base font medium hover bg gray focus outline none focus ring gray focus ring focus ring offset hover text gray dark bg gray dark text gray dark border gray dark hover text white dark hover bg gray dark focus ring gray onClick gt setModal false ref cancelButtonRef gt Cancel lt button gt lt div gt lt div gt lt Transition Child gt lt div gt lt Dialog gt lt Transition Root gt Done Enable Dark Mode If you have been paying attention to the Tailwind classes of our component elements you must have seen something like dark text white This kind of style pattern is applied to the elements when dark mode is enabled We haven t enabled it yet so let s do that now Open your tailwind config js file and add the following darkMode class Inside layouts create a file called ThemeToggler js and add a button that will toggle between light and dark mode ThemeToggler jsexport default function ThemeToggler return lt button ref themeToggleBtn type button className text gray dark text gray hover bg gray dark hover bg gray focus outline none rounded lg text sm p onClick gt handleThemeToggle gt lt svg ref themeToggleDarkIcon className hidden w h fill currentColor viewBox xmlns gt lt path d M A a z gt lt path gt lt svg gt lt svg ref themeToggleLightIcon className hidden w h fill currentColor viewBox xmlns gt lt path d M a va Va zm a zm l a l a zm a l a l a zM a h a hzm a va v a zM A l a l zm l a l a zM a Ha hz fillRule evenodd clipRule evenodd gt lt path gt lt svg gt lt button gt Create a useRef hook to access the above theme toggle button theme toggle light icon and theme toggle dark icon import useRef from react const themeToggleBtn useRef const themeToggleLightIcon useRef const themeToggleDarkIcon useRef Add refs to the toggle button dark icon and light icon SVGs respectively like this ref themeToggleBtn ref themeToggleDarkIcon ref themeToggleLightIcon For the button add an onClick event listener onClick gt handleThemeToggle Let s now create this function When the button is pressed it will check whether or not the user has a color theme set in local storage previously add remove the dark class and update local storage const handleThemeToggle gt themeToggleDarkIcon current classList toggle hidden themeToggleLightIcon current classList toggle hidden if localStorage getItem color theme if localStorage getItem color theme light document documentElement classList add dark localStorage setItem color theme dark else document documentElement classList remove dark localStorage setItem color theme light else if document documentElement classList contains dark document documentElement classList remove dark localStorage setItem color theme light else document documentElement classList add dark localStorage setItem color theme dark Next when the component renders we want to either set the dark or light mode by checking previous user preference or settings useEffect gt if localStorage getItem color theme dark color theme in localStorage amp amp window matchMedia prefers color scheme dark matches document documentElement classList add dark themeToggleLightIcon current classList remove hidden else document documentElement classList remove dark themeToggleDarkIcon current classList remove hidden Final code for ThemeToggler js ThemeToggler jsimport useEffect useRef from react export default function ThemeToggler const themeToggleBtn useRef const themeToggleLightIcon useRef const themeToggleDarkIcon useRef useEffect gt if localStorage getItem color theme dark color theme in localStorage amp amp window matchMedia prefers color scheme dark matches document documentElement classList add dark themeToggleLightIcon current classList remove hidden else document documentElement classList remove dark themeToggleDarkIcon current classList remove hidden const handleThemeToggle gt themeToggleDarkIcon current classList toggle hidden themeToggleLightIcon current classList toggle hidden if localStorage getItem color theme if localStorage getItem color theme light document documentElement classList add dark localStorage setItem color theme dark else document documentElement classList remove dark localStorage setItem color theme light else if document documentElement classList contains dark document documentElement classList remove dark localStorage setItem color theme light else document documentElement classList add dark localStorage setItem color theme dark return lt button ref themeToggleBtn type button className text gray dark text gray hover bg gray dark hover bg gray focus outline none rounded lg text sm p onClick gt handleThemeToggle gt lt svg ref themeToggleDarkIcon className hidden w h fill currentColor viewBox xmlns gt lt path d M A a z gt lt path gt lt svg gt lt svg ref themeToggleLightIcon className hidden w h fill currentColor viewBox xmlns gt lt path d M a va Va zm a zm l a l a zm a l a l a zM a h a hzm a va v a zM A l a l zm l a l a zM a Ha hz fillRule evenodd clipRule evenodd gt lt path gt lt svg gt lt button gt Finally to apply dark mode to the body of our application add the following in index css It will add our own default base styles for the body layer base body apply bg white dark bg gray Let s quickly add a navigation component and we will test the logout and dark mode functionalities Navigation The navigation will contain theme toggler logout and profile icons Inside layouts create a file called Header js Header jsimport LogoutIcon from heroicons react outline import useState from react import Link from react router dom import useAuth from contexts AuthContext import Logout from accounts Logout import ThemeToggler from ThemeToggler export default function Header const modal setModal useState false const currentUser useAuth return lt gt lt nav className px px sm px py bg gray border gray dark bg gray dark border gray text gray text sm rounded border dark text white gt lt div className container mx auto flex flex wrap items center justify between gt lt Link to className flex gt lt span className self center text lg font semibold whitespace nowrap text gray dark text white gt Chat App lt span gt lt Link gt lt div className flex md order gt lt ThemeToggler gt currentUser amp amp lt gt lt button className text gray dark text gray hover bg gray dark hover bg gray focus outline none rounded lg text sm p onClick gt setModal true gt lt LogoutIcon className h w aria hidden true gt lt button gt lt Link to profile className text gray dark text gray hover bg gray dark hover bg gray focus outline none rounded full text sm p gt lt img className h w rounded full src currentUser photoURL alt gt lt Link gt lt gt lt div gt lt div gt lt nav gt modal amp amp lt Logout modal modal setModal setModal gt lt gt We used conditional rendering to display the logout and profile icons only when the user is authenticated The modal state will be used to render the Logout modal for confirmation Finally let s render Header js inside App js App jsimport Header from components layouts Header Add this lt AuthProvider gt lt Router gt lt Header gt And this lt ErrorMessage gt lt Routes gt lt Route exact path register element lt Register gt gt lt Route exact path login element lt Login gt gt lt Route exact path profile element lt Profile gt gt lt Routes gt lt Router gt lt AuthProvider gt To test this go to http localhost profile You will get something like this when dark mode is enabled The logout modal with light mode Great moving on to private routes Private Route Routes such as profile should only be accessed if the user is logged in To make such components private let s go ahead and create a higher order component that will wrap them Inside the utils folder create a file called WithPrivateRoute js WithPrivateRoute jsimport Navigate from react router dom import useAuth from contexts AuthContext const WithPrivateRoute children gt const currentUser useAuth If there is a current user it will render the passed down component if currentUser return children Otherwise redirect to the login route return lt Navigate to login gt export default WithPrivateRoute We can now use this higher order component to wrap Profile jsThe final look of App js App jsimport BrowserRouter as Router Routes Route from react router dom import AuthProvider from contexts AuthContext import Register from components accounts Register import Login from components accounts Login import Profile from components accounts Profile import WithPrivateRoute from utils WithPrivateRoute import Header from components layouts Header import ErrorMessage from components layouts ErrorMessage function App return lt AuthProvider gt lt Router gt lt Header gt lt ErrorMessage gt lt Routes gt lt Route exact path register element lt Register gt gt lt Route exact path login element lt Login gt gt lt Route exact path profile element lt WithPrivateRoute gt lt Profile gt lt WithPrivateRoute gt gt lt Routes gt lt Router gt lt AuthProvider gt export default App You can test this by trying to access the profile page without logging in This marks the end of the frontend section for authentication Let s now get started with Express to verify users for subsequent requests Express Server Express Boilerplate The backend is going to be an independent app so in a new terminal type in the following npm init yThis will create a package json file Open it up and let s modify a couple of things First we are going to use ES modules import syntax so let s enable it type module We are also going to use nodemon so that we don t need to restart our server every time we make changes If you haven t already install it globally npm install g nodemonThen add the following to the scripts we will create server index js next start nodemon server index js Your package json should look like this name chat app version description main index js type module scripts test echo Error no test specified amp amp exit start nodemon server index js keywords author license ISC dependencies express Now install Express npm i expressCreate a folder named server cd into it and create index js file This is where we will set up our server mkdir servercd servertouch index jsInside index js let s add a simple endpoint to fire up and test our server index jsimport express from express const app express app use express json app use express urlencoded extended false app get req res gt res send working fine const PORT app listen PORT gt console log Server listening on port PORT To test it cd npm startNow if you go to http localhost on your browser you should see the “working fine output Enabling Cors We need to enable cors to allow React to send requests to Express Install cors npm i corsAnd inside index jsimport cors from cors Add this to the list of importsapp use cors Use the cors middleware Using Environment Variables To use environment variables let s install dotenvnpm i dotnevThen create a env file at the root of your projecttouch envOpen it and add the portPORT Then in index js import dotenv and access the PORT variable we just created import dotenv from dotenv Add to import listdotenv config Configure dotenv to access the env variablesconst PORT process env PORT Use this instead of hardcoding it like before Connect with React Now that we have enabled cors let s test this by sending a request from React Go to the frontend folder and open up Header js from components layouts Add the following useEffect hook Note that this is just for testing purposes You can get rid of it later useEffect gt const fetchData async gt try const res await fetch http localhost console log await res text catch e console log e fetchData We are making a request to this http localhost endpoint using the built in fetch API and logging the response to the console If you head over to your React app at http localhost you should see the “working fine output in the console Dope React can communicate with the backend now However what we want to do is prevent React from getting a response if a verified user token is not sent We will do things Send the Firebase token from the frontend to the backendCreate a middleware in Express to verify the token Sending Firebase Token to Express Again open Header js and let s modify the previous request to send the authentication token as a header Authorization Bearer token How can we get the token Firebase makes this really easy Header jsimport auth from config firebase useEffect gt const fetchData async gt try const user auth currentUser const token user amp amp await user getIdToken const payloadHeader headers Content Type application json Authorization Bearer token const res await fetch http localhost payloadHeader console log await res text catch e console log e fetchData First we imported auth from our firebase config We can use this to get the current user instance getIdToken returns the token if it has not expired or if it will not expire in the next five minutes Otherwise this will refresh the token and return a new one Now if you go to http localhost network tab you can see the Authorization header being sent as well This is looking good The next step is to verify the token in our backend Creating the Middleware The middleware we are going to create will access the request to find the token Then we will verify it How Again Firebase to the rescue Firebase has a backend module that allows us to verify the token Let s install it Inside your root directory where package json and frontend folder are located npm i firebase adminAccording to the docs to use Firebase admin SDK we need x A Firebase project x A Firebase Admin SDK service account to communicate with Firebase This service account is created automatically when you create a Firebase project or add Firebase to a Google Cloud project A configuration file with your service account s credentials We have done the first To get the service account go to your Firebase Dashboard and open Settings in the side panel Then click the Service Accounts tab and click Generate New Private Key then confirm by clicking Generate Key Once you download the JSON file containing the keys go back to your project and navigate to the server folder Create a folder called config and inside it create a file called serviceAccountKey json This is where we will put the generated keys cd servermkdir configcd configtouch serviceAccountKey jsonAfter copy pasting the keys into this file create another file inside this config folder called firebase config jstouch firebase config jsThen open this file and firebase config jsimport initializeApp cert from firebase admin app import getAuth from firebase admin auth import serviceAccountKey from serviceAccountKey json assert type json const app initializeApp credential cert serviceAccountKey const auth getAuth app export default auth We imported the JSON file with the Firebase configurations and used it to initialize the Firebase SDK We then exported auth to use it elsewhere Next inside the server folder create a folder called middleware Inside middleware create a file called VerifyToken jsThen open VerifyToken js and add the following VerifyToken jsimport auth from config firebase config js export const VerifyToken async req res next gt const token req headers authorization split try const decodeValue await auth verifyIdToken token if decodeValue req user decodeValue return next catch e return res json message Internal Error First we imported the Firebase auth we created earlier const token req headers authorization split Here we are splitting the authorization header to get the token from the request auth verifyIdToken token will decode the token to its associated user Finally we check if this decoded value is the same as the user sending the request Let s now use this middleware in index jsimport VerifyToken from middlewares VerifyToken js app use VerifyToken Add this middlewareindex js will look like this index jsimport express from express import cors from cors import dotenv from dotenv import VerifyToken from middlewares VerifyToken js const app express dotenv config app use cors app use express json app use express urlencoded extended false app use VerifyToken const PORT process env PORT app get req res gt res send working fine app listen PORT gt console log Server listening on port PORT Now if you go back to http localhost and refresh you will see “working fine outputted on the console However if you replace the token with some random value or remove the header Express will reject the request Perfect Everything is working now Final Thoughts Got lost somewhere throughout the process No problem check out the project on GitHub or ask your question in the comments section Feedback or comment let me know down below Thanks 2022-09-12 07:03:12
医療系 医療介護 CBnews 【解説】医療連携推進法人の活用、どこまで-2040年を見据えた医療・介護改革 https://www.cbnews.jp/news/entry/20220912161620 社会保障 2022-09-12 16:35:00
金融 RSS FILE - 日本証券業協会 インターネット取引に係るシステム障害件数 https://www.jsda.or.jp/shiryoshitsu/toukei/inter/index.html 取引 2022-09-12 09:00:00
金融 日本銀行:RSS CPMI/IOSCO報告書「顧客清算:アクセスおよびポータビリティ」 http://www.boj.or.jp/announcements/release_2022/rel220912c.htm cpmiiosco 2022-09-12 17:00:00
金融 日本銀行:RSS フェイルの発生状況(8月) http://www.boj.or.jp/statistics/set/bffail/sjgb2208.pdf 発生 2022-09-12 16:30:00
ニュース @日本経済新聞 電子版 お悩みに「AIブッダ」が回答 京都大学、AR活用 https://t.co/nbpat5U6l2 https://twitter.com/nikkei/statuses/1569228758841958400 京都大学 2022-09-12 07:37:45
ニュース @日本経済新聞 電子版 給食「全員無償化」広がる 子育て世帯支援で自治体導入 https://t.co/Y976eAN6rw https://twitter.com/nikkei/statuses/1569224124354146304 自治体 2022-09-12 07:19:20
海外ニュース Japan Times latest articles Japan plans to reopen to independent travelers in major shift, report says https://www.japantimes.co.jp/news/2022/09/12/national/border-independent-tourists-visa-waiver/ Japan plans to reopen to independent travelers in major shift report saysTourists who will need to have been vaccinated three times or submit a negative test result under the new policy may be able to enter 2022-09-12 16:17:36
ニュース BBC News - Home King Charles III to address Houses of Parliament before Scotland trip https://www.bbc.co.uk/news/uk-62874346?at_medium=RSS&at_campaign=KARANGA edinburgh 2022-09-12 07:46:11
ニュース BBC News - Home Queen's lying-in-state: Details announced on how to pay respects https://www.bbc.co.uk/news/uk-62872323?at_medium=RSS&at_campaign=KARANGA queues 2022-09-12 07:26:47
ニュース BBC News - Home National League games to go ahead from Monday as football restarts in England https://www.bbc.co.uk/sport/football/62869041?at_medium=RSS&at_campaign=KARANGA National League games to go ahead from Monday as football restarts in EnglandNational League fixtures will go ahead on Monday after football paused as a mark of respect following the death of Queen Elizabeth II 2022-09-12 07:06:08
ニュース BBC News - Home UK economy grew slower than expected in July https://www.bbc.co.uk/news/business-62874496?at_medium=RSS&at_campaign=KARANGA boost 2022-09-12 07:36:50
ニュース BBC News - Home Lynette White: Tony Paris, one of Cardiff Three, dies https://www.bbc.co.uk/news/uk-wales-62873185?at_medium=RSS&at_campaign=KARANGA cardiff 2022-09-12 07:38:36
ニュース BBC News - Home NFL week one: Tom Brady's Tampa Bay Buccaneers beat Dallas Cowboys https://www.bbc.co.uk/sport/american-football/62873590?at_medium=RSS&at_campaign=KARANGA NFL week one Tom Brady x s Tampa Bay Buccaneers beat Dallas CowboysTom Brady s Tampa Bay Buccaneers win their first game of the new NFL season with a dominant defensive display against the Dallas Cowboys 2022-09-12 07:35:11
北海道 北海道新聞 藤沢周平さんに中国の魯迅文学賞 日本人で2人目、大江さん以来 https://www.hokkaido-np.co.jp/article/729725/ 文芸春秋 2022-09-12 16:16:00
北海道 北海道新聞 救急車到着遅れ、男性患者が死亡 岐阜・中津川、通信指令が誤指示 https://www.hokkaido-np.co.jp/article/729724/ 中津川市消防本部 2022-09-12 16:15:00
ニュース Newsweek アーチーとリリベットはエリザベス女王の葬儀に参列する? https://www.newsweekjapan.jp/stories/world/2022/09/post-99597.php ウィリアム皇太子の子供たちは出席予定まだ公式発表はされていないものの、ナウ・トゥ・ラブによればウィリアム王子の人の子供たちージョージ王子、シャーロット王女、ルイ王子は葬儀に出席する予定だという。 2022-09-12 16:56:51
ニュース Newsweek 女王の逝去前、メーガン妃は夫に続く暴露本の出版をほのめかしていた https://www.newsweekjapan.jp/stories/world/2022/09/post-99598.php 2022-09-12 16:55:19
ニュース Newsweek 「伝説は本当だった!」10万平方キロの「白く光る海」が衛星写真で捉えられる https://www.newsweekjapan.jp/stories/world/2022/09/10-168.php 万平方キロで発光し、夜も続いていたガネーシャ号が光る海に遭遇したのは、年月のことだ。 2022-09-12 16:30:29
ニュース Newsweek 英新首相トラスを待つ2つの大問題 https://www.newsweekjapan.jp/stories/world/2022/09/post-99596.php 支持率の行方に疑問符インフレ率を引き下げて生活費上昇に対処するのは、経済的にも政治的にも難しい課題だ。 2022-09-12 16:15:00
IT 週刊アスキー 『DQウォーク』で「3周年記念イベント 黄金の勇気」が開催!メタルキング装備が手に入る「3周年記念ふくびき」も登場 https://weekly.ascii.jp/elem/000/004/105/4105190/ 位置情報 2022-09-12 16:40:00
IT 週刊アスキー povo2.0の新規加入で、「7日間データ使い放題」のコードプレゼントキャンペーン https://weekly.ascii.jp/elem/000/004/105/4105194/ 月日 2022-09-12 16:40:00
IT 週刊アスキー 横浜の街をめぐりながら楽しもう! 回遊型アートイベント「ミナトノアート2022」が10月14日~31日に開催 https://weekly.ascii.jp/elem/000/004/105/4105156/ 中華街駅 2022-09-12 16:30:00
IT 週刊アスキー 1週間限定!Steam版『マブラヴ オルタネイティヴ トータル・イクリプス』10%割引セールを開催中 https://weekly.ascii.jp/elem/000/004/105/4105188/ anchor 2022-09-12 16:30:00
IT 週刊アスキー 豚トロ×豚バラ=最強! 夢のコラボ定食がやよい軒から新登場 https://weekly.ascii.jp/elem/000/004/105/4105192/ 豚バラ 2022-09-12 16:30:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)