投稿時間:2023-05-31 02:31:58 RSSフィード2023-05-31 02:00 分まとめ(39件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… AppleのMRヘッドセット用OS『xrOS』の名称が「App Store Connect」で確認される https://taisy0.com/2023/05/31/172314.html apple 2023-05-30 16:19:45
IT 気になる、記になる… Apple、「Apple Music Classical」のAndroid向け公式アプリを配信開始 https://taisy0.com/2023/05/31/172310.html android 2023-05-30 16:07:16
IT InfoQ Unlocking Software Engineering Potential for Better Products https://www.infoq.com/news/2023/05/software-engineering-potential/?utm_campaign=infoq_content&utm_source=infoq&utm_medium=feed&utm_term=global Unlocking Software Engineering Potential for Better ProductsBecoming an empowered team means solving problems rather than shipping features Empowering software engineers and involving them early in discovery work can result in better products If we measure outcomes rather than output we can also hold teams accountable Supporting software engineers to empower them means trusting them and getting out of their way By Ben Linders 2023-05-30 16:22:00
AWS AWS Partner Network (APN) Blog Boost Your Solution Adoption with Accenture Future Talent Platform on AWS https://aws.amazon.com/blogs/apn/boost-your-solution-adoption-with-accenture-future-talent-platform-on-aws/ Boost Your Solution Adoption with Accenture Future Talent Platform on AWSLearn how Accenture engineered a cloud native SaaS learning platform that enables users to succeed in fast paced environments Take a look at why quick adoption is essential for an organization to acquire new knowledge adapt mindsets and develop new capabilities required to deliver changing business initiatives in a timely way Accenture s Future Talent Platform enables general or highly focused training to guide customers partners or employees to get the most out of new technologies or programs 2023-05-30 16:30:53
AWS AWS Database Blog Automate the migration of Microsoft SSIS packages to AWS Glue with AWS SCT https://aws.amazon.com/blogs/database/automate-the-migration-of-microsoft-ssis-packages-to-aws-glue-with-aws-sct/ Automate the migration of Microsoft SSIS packages to AWS Glue with AWS SCTWhen you migrate Microsoft SQL Server workloads to AWS you might want to automate migration and minimize changes to existing applications but still use a cost effective option without commercial licenses and reduce operational overhead For example SQL Server workloads often use SQL Server Integration Services SSIS to extract transform and load ETL data In this … 2023-05-30 16:52:07
AWS AWS Machine Learning Blog Analyze Amazon SageMaker spend and determine cost optimization opportunities based on usage, Part 5: Hosting https://aws.amazon.com/blogs/machine-learning/part-5-analyze-amazon-sagemaker-spend-and-determine-cost-optimization-opportunities-based-on-usage-part-5-hosting/ Analyze Amazon SageMaker spend and determine cost optimization opportunities based on usage Part HostingIn we launched AWS Support Proactive Services as part of the AWS Enterprise Support plan Since its introduction we have helped hundreds of customers optimize their workloads set guardrails and improve visibility of their machine learning ML workloads cost and usage In this series of posts we share lessons learned about optimizing costs in … 2023-05-30 16:50:46
AWS AWS Machine Learning Blog Analyze Amazon SageMaker spend and determine cost optimization opportunities based on usage, Part 4: Training jobs https://aws.amazon.com/blogs/machine-learning/part-4-analyze-amazon-sagemaker-spend-and-determine-cost-optimization-opportunities-based-on-usage-part-4-training-jobs/ Analyze Amazon SageMaker spend and determine cost optimization opportunities based on usage Part Training jobsIn we launched AWS Support Proactive Services as part of the AWS Enterprise Support plan Since its introduction we ve helped hundreds of customers optimize their workloads set guardrails and improve the visibility of their machine learning ML workloads cost and usage In this series of posts we share lessons learned about optimizing costs in … 2023-05-30 16:50:32
AWS AWS Machine Learning Blog Analyze Amazon SageMaker spend and determine cost optimization opportunities based on usage, Part 3: Processing and Data Wrangler jobs https://aws.amazon.com/blogs/machine-learning/part-3-analyze-amazon-sagemaker-spend-and-determine-cost-optimization-opportunities-based-on-usage-part-3-processing-and-data-wrangler-jobs/ Analyze Amazon SageMaker spend and determine cost optimization opportunities based on usage Part Processing and Data Wrangler jobsIn we launched AWS Support Proactive Services as part of the AWS Enterprise Support plan Since its introduction we ve helped hundreds of customers optimize their workloads set guardrails and improve the visibility of their machine learning ML workloads cost and usage In this series of posts we share lessons learned about optimizing costs in … 2023-05-30 16:50:19
AWS AWS Machine Learning Blog Analyze Amazon SageMaker spend and determine cost optimization opportunities based on usage, Part 2: SageMaker notebooks and Studio https://aws.amazon.com/blogs/machine-learning/part-2-analyze-amazon-sagemaker-spend-and-determine-cost-optimization-opportunities-based-on-usage-part-2-sagemaker-notebooks-and-studio/ Analyze Amazon SageMaker spend and determine cost optimization opportunities based on usage Part SageMaker notebooks and StudioIn we launched AWS Support Proactive Services as part of the AWS Enterprise Support offering Since its introduction we have helped hundreds of customers optimize their workloads set guardrails and improve the visibility of their machine learning ML workloads cost and usage In this series of posts we share lessons learned about optimizing costs … 2023-05-30 16:50:06
AWS AWS Machine Learning Blog Analyze Amazon SageMaker spend and determine cost optimization opportunities based on usage, Part 1 https://aws.amazon.com/blogs/machine-learning/part-1-analyze-amazon-sagemaker-spend-and-determine-cost-optimization-opportunities-based-on-usage-part-1/ Analyze Amazon SageMaker spend and determine cost optimization opportunities based on usage Part Cost optimization is one of the pillars of the AWS Well Architected Framework and it s a continual process of refinement and improvement over the span of a workload s lifecycle It enables building and operating cost aware systems that minimize costs maximize return on investment and achieve business outcomes Amazon SageMaker is a fully managed machine learning ML … 2023-05-30 16:49:45
AWS AWS Machine Learning Blog High-quality human feedback for your generative AI applications from Amazon SageMaker Ground Truth Plus https://aws.amazon.com/blogs/machine-learning/high-quality-human-feedback-for-your-generative-ai-applications-from-amazon-sagemaker-ground-truth-plus/ High quality human feedback for your generative AI applications from Amazon SageMaker Ground Truth PlusAmazon SageMaker Ground Truth Plus helps you prepare high quality training datasets by removing the undifferentiated heavy lifting associated with building data labeling applications and managing the labeling workforce All you do is share data along with labeling requirements and Ground Truth Plus sets up and manages your data labeling workflow based on these requirements From … 2023-05-30 16:13:43
AWS AWS Media Blog FOX ups resolution, drops latency with AWS-powered streaming https://aws.amazon.com/blogs/media/fox-ups-resolution-drops-latency-with-aws-powered-streaming/ FOX ups resolution drops latency with AWS powered streamingAdvanced video delivery workflow rolls out across the network s digital sports coverage after reaching M peak viewers during NFL championship game FOX s commitment to innovating its cloud based media production and delivery platform continues to pay off as seen with its latest production for the National Football League NFL championship match up An implementation … 2023-05-30 16:00:46
AWS AWS Inawisdom: How Insurance Companies are Using IDP to Optimize Document Processing https://www.youtube.com/watch?v=yXpd8gPfows Inawisdom How Insurance Companies are Using IDP to Optimize Document ProcessingThe insurance industry has billions of historical documents with hundreds of thousands more being generated each and every day The documents in varying formats are used both internally and with other insurers to agree terms assess risk and create accurate quotes Historically each document can take a few hours or even days to manually process and needs to be loaded into each company s systems Inawisdom is helping several companies to reduce this processing time to minutes by automating the process using Intelligent Document Processing IDP saving time increasing the accuracy and readying the data for further analysis giving valuable insights back to the business IDP uses the latest AI services Amazon s Textract to extract text Amazon Comprehend to classify and detect entries in the documents and custom models with labelled grown truth in SageMaker This architecture will look at these services alongside the pre processing processing and post processing challenges and showcase how to jointly leverage these services for the best success Using IDP one customer achieved an accuracy of and a more than x reduction in processing time across over £ million worth of business Check out more resources for architecting in the AWS​​​cloud AWS AmazonWebServices CloudComputing ThisIsMyArchitecture 2023-05-30 16:20:29
AWS AWS - Webinar Channel Get Answers From Data in Seconds with Amazon QuickSight Q“- AWS Analytics in 15 https://www.youtube.com/watch?v=678Hr0Fpmws Get Answers From Data in Seconds with Amazon QuickSight Q“ AWS Analytics in See how Amazon QuickSight Q can help bring data and insights to all users within an organization through ML powered natural language queries so that you can use business intelligence more effectively to make decisions despite various tools and data resources Learning Objectives Objective See how users get answers from their data in just seconds and save to a personal pinboard Objective Learn how to get started with Q fast with AI enhanced automated data prep Objective Explore the latest “Why and “Forecasting question types To learn more about the services featured in this talk please visit To download a copy of the slide deck from this webinar visit 2023-05-30 16:15:00
python Pythonタグが付けられた新着投稿 - Qiita 【完全保存版】Python 要素の並べ替えについてあれこれ https://qiita.com/kubochiro/items/4d8c03163418aec783c8 sorted 2023-05-31 01:54:27
Git Gitタグが付けられた新着投稿 - Qiita ブランチ名を考えるのが面倒くさいのでAIに考えさせる https://qiita.com/dsyuuto/items/fa876b6644fafeea1f7b featureissues 2023-05-31 01:21:02
Git Gitタグが付けられた新着投稿 - Qiita 【Git】特定のファイルを管理対象から除外する方法 https://qiita.com/P-man_Brown/items/255e827280e0f8a4d7f0 gitrmcachedpathtofile 2023-05-31 01:20:54
海外TECH MakeUseOf What Is Qi2 Wireless Charging and How Is It Better Than Qi? https://www.makeuseof.com/what-is-qi2-wireless-charging/ android 2023-05-30 16:01:17
海外TECH MakeUseOf Learn How to Make Paper Airplanes With These 8 Paper Craft Websites https://www.makeuseof.com/tag/learn-paper-airplanes-paper-craft-websites/ Learn How to Make Paper Airplanes With These Paper Craft WebsitesLearning to make paper planes is not just about creasing the paper at the folds and throwing it up in the air It is aeronautical science at its most fundamental 2023-05-30 16:01:17
海外TECH DEV Community Generative AI with Azure OpenAI (DALL-E Overview) https://dev.to/esdanielgomez/generative-ai-with-azure-openai-dall-e-overview-2pji Generative AI with Azure OpenAI DALL E Overview Hey there In this article we ll learn about Generative AI and how to use the Azure OpenAI service for image generation with DALL E Generative Artificial Intelligence is a type of AI that creates new and original content based on what it has learned from previous data It can be used to generate text images music and more Azure OpenAIAzure OpenAI is part of the Azure Cognitive Services that uses generative AI models In this sense these are the workloads that we can consider Generating Natural Language Generating Code Generating Images For our Azure OpenAI overview we ll exemplify this scenario Generate images with DALL E Exploring Azure OpenAI Create Azure OpenAI service As a first point within Azure we ll have to create a new OpenAI resource like any other Here in addition to the subscription and resource group we must specify the name region and the pricing tier for the new resource With the service created here we can see the resource overview keys amp endpoints and the Go to Azure OpenAI Studio option to go to the low code dashboard Azure OpenAI Studio And here we have it The Azure OpenAI portal To work with DALL E in the portal we must go to the DALL·E playground section and start generating images with the prompts that we specify For each image generated these will be our available options Copy prompt Generate a new image with the same prompt Download the image Show code to call the model Delete image To generate an example of consuming DALL E in Python this would be an example of how we can generate the code from the Show Code option in a generated image Thanks for reading If you have any questions or ideas in mind it will be a pleasure to be able to be in communication with you and together exchange knowledge with each other If you would like to learn more about Azure OpenAI this Microsoft Learn module is a good option Introduction to Azure OpenAI Service See you on Twitter LinkedIn 2023-05-30 16:57:34
海外TECH DEV Community Joins in DBMS https://dev.to/aryan_shourie/joins-in-dbms-4cf1 Joins in DBMSDatabase Management System DBMS is a software or technology used to manage data from a database DBMS provides an interface to perform various operations like database creation storing data in it updating data creating a table in the database which is used in different applications A DBMS Join is defined as the combination of a Cartesian Product followed by a selection process A Join operation pairs two tuples from different relations if and only if a given Join condition is satisfied Joins are an essential operation in Database Management Systems and are used to combine data from multiple tables in order to perform complex queries and data analysis Types of Joins in DBMSINNER JOINLEFT JOINRIGHT JOINFULL OUTER JOINConsider the two tables below as follows Employee Table Project Table INNER JOINIn DBMS the Inner Join is such type of Join that returns all rows from both the participating tables where the key record of one table is equal to key records in another table It basically selects the records that have matching values in both tables Syntax SELECT table column table column table column FROM table INNER JOIN table ON table matching column table matching column Example Query SELECT EMPLOYEE EMP NAME PROJECT DEPARTMENT FROM EMPLOYEE INNER JOIN PROJECT ON PROJECT EMP ID EMPLOYEE EMP ID Output LEFT JOINIn DBMS the Left Join includes all rows from the left table of the Join clause and the unmatched rows from the right table with NULL values for the selected columns It basically selects all records from the left table and the matching records from the right table Syntax SELECT table column table column table column FROM table LEFT JOIN table ON table matching column table matching column Example Query SELECT EMPLOYEE EMP NAME PROJECT DEPARTMENT FROM EMPLOYEE LEFT JOIN PROJECT ON PROJECT EMP ID EMPLOYEE EMP ID Output RIGHT JOINIn DBMS the Right Join includes all rows from the right table of the Join clause and the unmatched rows from the left table with NULL values for the selected columns It basically selects all records from the right table and the matching records from the left table Syntax SELECT table column table column table column FROM table RIGHT JOIN table ON table matching column table matching column Example Query SELECT EMPLOYEE EMP NAME PROJECT DEPARTMENT FROM EMPLOYEE RIGHT JOIN PROJECT ON PROJECT EMP ID EMPLOYEE EMP ID Output FULL OUTER JOINIn DBMS the Full Outer Join includes the matching rows from the left table and the right table of the Join clause and the unmatched rows from both the left and right tables with NULL values for selected columns Syntax SELECT table column table column table column FROM table FULL JOIN table ON table matching column table matching column Example Query SELECT EMPLOYEE EMP NAME PROJECT DEPARTMENT FROM EMPLOYEE FULL JOIN PROJECT ON PROJECT EMP ID EMPLOYEE EMP ID Output And thats it You have successfully learnt all about the Joins in DBMS Connect with me on Linkedin LinkedinDo check out my Github for amazing projects GithubView my Personal Portfolio Aryan s Portfolio 2023-05-30 16:47:50
海外TECH DEV Community Top 7 Featured DEV Posts from the Past Week https://dev.to/devteam/top-7-featured-dev-posts-from-the-past-week-1cb6 Top Featured DEV Posts from the Past WeekEvery Tuesday we round up the previous week s top posts based on traffic engagement and a hint of editorial curation The typical week starts on Monday and ends on Sunday but don t worry we take into account posts that are published later in the week I created unique CSS patternsIn this post afif showcases their library of over unique CSS patterns made by scratch all using the same code structure Grab a nice pattern and show us the results on your favorite site I created unique CSS patterns The best collection Temani Afif・May ・ min read showdev webdev css codepen JWT Authentication in React with react routerHere sanjayttg explores the seamless integration between JWT authentication with React and react router Learn how to handle public routes secure authenticated routes and utilize the axios library to make API requests with the authentication token JWT Authentication in React with react router Sanjay Arya・May ・ min read react router token jwt Deploy Hugging Face Models on Serverless GPUHugging Face is a platform focused on making AI and data science more accessible dhanushreddy shows you how to get started on your own by using Serverless GPUs on a Pay As You Go model Deploy Hugging Face Models on Serverless GPU Dhanush Reddy・May ・ min read huggingface serverless gpu machinelearning What s new in ES Each year new features are added to ECMAScript the specification that JavaScript is based on Following up on last year s ES jasmin covers the latest features announced for ES including shebang grammar array improvements and a more functional version of sort What s new in ES Jasmin Virdi・May ・ min read javascript webdev programming news Future of CSS Popover API linktwenty looks at two exciting features coming to CSS and how well they work when paired together Popover API is awesome on its own but even better when paired with anchor positioning Future of CSS Popover API Andrew Bone・May ・ min read css webdev javascript ux Keeping up with my cat s using a RaspberryPiLike many of us cat owners fdocr was shocked at how they re essentially potty trained from birth Equally shocking is the smell that comes with it Tech is meant to make our lives easier so let s do just that with an IoT solution Keeping up with my cat s using a RaspberryPi Fernando・May ・ min read raspberrypi python automation A Practical Overview on Architecture Decision Records ADR ctaverna wants to show you how to start writing up ADRs and why this could be your most valuable action as a software architect A practical overview on Architecture Decision Records ADR Claudio Taverna・May ・ min read softwareengineering webdev architecture documentation That s it for our weekly Top for this Tuesday Keep an eye on dev to this week for daily content and discussions and be sure to keep an eye on this series in the future You might just be in it 2023-05-30 16:42:15
海外TECH DEV Community Integrating Elasticsearch with Node.js Applications https://dev.to/limaleandro1999/integrating-elasticsearch-with-nodejs-applications-i18 Integrating Elasticsearch with Node js Applications Integrating Elasticsearch with Node js ApplicationsThese days data is growing exponentially and keeping it organized and up to date is essential for any web based applications One of the most popular solutions to do this is Elasticsearch It s a search engine and data analysis tool that helps developers to store index retrieve and manage data in real time In this tutorial we ll learn how to integrate Elasticsearch into a Node js project We ll use some existing Node js packages to do the job and we ll discuss the benefits that Elasticsearch brings to your applications What Is Elasticsearch Elasticsearch is a search engine system that helps you to store search and analyse data in real time It s based on the Apache Lucene library and it s a distributed open source search and analytics engine Elasticsearch is written in Java and its source code is available on Github It provides a distributed multitenant capable full text search engine with an HTTP web interface and schema free JSON documents It supports various types of data including text numbers dates geo points and complex data such as objects and nested objects Advantages of Using ElasticsearchUsing Elasticsearch in your project can bring great benefits High Performances Elastisearch is built to query large datasets in milliseconds It is based on Apache Lucene an open source search engine Scalability Elasticsearch is built on top of Apache Lucene and it s designed to be easily distributed and scaled out This makes it ideal for handling large amounts of data You can scale out an Elasticsearch cluster to as many nodes as you need to handle large volumes of data Real time Analytics You can use Elasticsearch to power real time analytics dashboards This is especially useful if you need to query large datasets and display results in real time Full text search Elasticsearch is a full text search engine meaning that it can search through unstructured data This is useful if you need to search through large datasets such as log files or text documents Clustering You can group individual documents into larger clusters This makes it easy to find related documents quickly and helps you analyze data in context Integrating Elasticsearch with Node jsTo use Elasticsearch with Node js you ll need to install the official Elasticsearch client for Node js This npm module is a client that wraps the REST API functionality of Elasticsearch Once you have the Elasticsearch client installed you should create a connection to your Elasticsearch cluster This connection will be used to send requests to the cluster and retrieve data const Client require elastic elasticsearch create a new Client const client new Client node http localhost auth username elastic password changeme connect to the clientclient connect You can then use the client s APIs to send requests to the cluster and retrieve data For example to search for documents in an index you can use the search API client search index my index body query match all then response gt do something with the response You can refer to the official Elasticsearch client for Node js documentation for more information on how to use the APIs If you need to manage your data in a more efficient way you can also consider using the Nest js framework Nest js is a Node js framework that helps you to build efficient scalable and reliable server side applications It supports features such as TypeScript GraphQL and supports integration with databases like PostgreSQL and MySQL ConclusionIn this tutorial we learned how to integrate Elasticsearch with Node js We also discussed the advantages of using the official Elasticsearch client for Node js and how Nest js can be used to manage data more efficiently Elasticsearch is a powerful search engine and data analysis tool and integrating it with Node js can bring significant benefits to your project With its fast search times and scalability it can provide your application with real time analytics and insights into your data What do you think about using Elasticsearch in your projects Let me know in the comments 2023-05-30 16:22:49
海外TECH DEV Community React and NodeJS Authentication with Refresh & Access Tokens: A Step-by-Step Guide https://dev.to/sukhjinderarora/understanding-refresh-access-token-based-authentication-in-react-and-nodejs-1j9e React and NodeJS Authentication with Refresh amp Access Tokens A Step by Step GuideThis article was originally published at The most common way of performing authentication in Single Page Applications SPA is through the use of JSON Web Tokens JWT While JWT based authentication is easy to implement there are some downsides to using JWT in SPAs that should be considered Security Since JWT is stateless and does not store any information on the server there s no way to invalidate it from the server side If a JWT is stolen or compromised an attacker can gain access to sensitive information Lack of Revocation As JWT is stateless it makes it difficult to revoke tokens from the server side when a user logs out or changes their password or to allow users to sign out from all devices Limited Validity Period As JWT is valid for a limited amount of time the users will have to log in to the application whenever the JWT expires which is not a good user experience We can avoid these issues either by Using Sessions or Using Refresh and Access tokens to authenticate users which I will cover in this article Before getting started let s first understand what refresh and access tokens are What are Access Tokens Access tokens are short lived tokens that are issued by an authorization server and are used to access protected resources Access tokens are passed in the header of an API request and are used to verify that the user has the necessary permissions to access the requested resource What are Refresh Tokens Refresh tokens are long lived tokens that are issued along with access tokens They are used to request a new access token when the current access token expires This allows the user to remain authenticated even if the access token has expired without having to re enter their credentials Getting StartedBefore starting you must have npm installed on your computer which comes bundled with Node js which you can install from here Folder Structure You can create the above directories with these commands mkdir refresh token auth appcd refresh token auth appmkdir client serverThis project is divided into two parts Node js amp Express application for the backend ReactJS application for the front end Creating Backend Application Run the following commands to initialize the Node js project and install the required dependencies cd refresh token auth app servernpm init ynpm install express jsonwebtoken cookie parser cors dotenv ms http errorsCreating Frontend Application Run the following commands to initialize the React project cd refresh token auth appnpx create react app client Authentication FlowNow that we have set up the project structure required for the application let s understand the general overview of how the refresh and access token based authentication will work in our application When a user first logs in to our application the server will generate an access token and a refresh token for the user The access token will be sent as a part of the response body while the refresh token will be sent as an httpOnly cookie The refresh token will also be stored in the database for each user When the access token is about to expire our application will automatically send a request to the server to refresh the access token also known as silent authentication Since we are storing the access token in memory instead of local storage to prevent XSS attacks our application will also perform silent authentication when the user refreshes the browser window When a user logs out of the application the server will remove the refresh token stored in the database and the cookie API EndpointsNow that we have a basic understanding of the authentication flow of our application let s list the API endpoints necessary for the application to work We will need these endpoints to make our application work POST auth sign up to allow users to sign up POST auth login to allow users to log in POST auth refresh to generate a new access token using the given refresh token POST auth logout to log out the user GET users list optional to get the list of users Folder StructureBefore we start writing these APIs let s create the folder structure required for the backend application You can create the above directories with these commands cd servermkdir controllers middlewares routes data utilstouch app js Creating Express ApplicationAdd the following boilerplate code to the app js file to create the express application const path require path require dotenv config const express require express const cors require cors const cookieParser require cookie parser const PORT NODE ENV process env const isDev NODE ENV development const app express if isDev app use cors origin http localhost optionsSuccessStatus credentials true app use express json type application json app use cookieParser process env COOKIE SECRET app use express static path join dirname public app get req res gt res sendFile path resolve dirname public index html app use req res next gt const error new Error Not Found error status next error app use error req res next gt console error xb m error if res headersSent return next error return res status error status json error status error status message error status error message Internal Server Error app listen PORT error gt if error console log Error in server setup return console log Server listening on Port PORT Here I am using dotenv middleware to load environment variables from the env file into the process env variable cors middleware to allow Cross Origin Resource Sharing CORS in development mode express json to parse the request body as JSON cookie parser middleware to parse cookies in the incoming request headers express static middleware to serve the static files from the public directory Error handler middleware ーwhich is executed when an error occurs in the application And Finally app listen method to create a new server and listen on the specified port defined by the PORT environment variable Add this code to the package json script section start node app js Environment variablesCreate a env file at the root of the server directory and add the following environment variables to that file PORT ACCESS TOKEN SECRET rGvElkhMpIHdQfslsC zprSYDDNIIfzRusLevTnfEvpFzdEiGpXzwEkghDxWxONRxeCvcrsziYEuFGutZX niTTQJylTba ydgURY krnwsfiCAQPBgc SlY nMRsDF MSQATlfuSXX BIKgDmFWwZAQqGScWKNiQOJEhcNjkpyFtaeUzK qpGRjqVLzbyhttUbAWdhN mvVgiHBrLlqpbFLIIebGHWEeznymyQNjLdxOkcNRBNmWRnRbamjeTJaHChebONLhGRWAFLwSLiNpEqcNSqg REFRESH TOKEN SECRET LbIiOVVMuKQAKnGiuWvxrypJrouogVYbJjrJJdBbqXLuKBUIa PzphvkjiUaEEFnpgCBRewvxPCIyHZpHrGRZjUtCmbjGpLqIetlgMlEOPTzrwYAkgAHBNNUzeZlwlzOSiCWbhqcwVqDyKYh llIm eBUVVlThNwTDsnLtcLBjhkzaBQqCUzZQmOLtTpCerjnzaWzlSvSyPzJ yemlkgFEZkiKPdoNrJPeaXNkkqECHNlZmccpCTSWPr RPR vjGltCRLnhJwMqBDYFpXcAHcvfzbXcEwkhEOimzoKaaMg LPpTw COOKIE SECRET AkjjwPUQTUPatxFvatytaYxHnKxkfytoQAoignerppxxgoghtUxnKhSeJXVLkbAZsHcnCFEhYOInuydrRJL xrjEFBSQNjQFKrYSQES zk etbBdums bo YuAueJMiFCeRNHUGknueFJHEa sfSVsfQLIBgXdWwmemRNYeqtpRmdxYtHeDwJqtoYWdLUonahQCzyuzD aJWwwSIGyLVeHSgBQ DDK stv IPLVrkVGMwhOGJkshNNdehpBkxsNNwjzlxRGNOhNmLdiPkFsAzjBzmwNQ ACCESS TOKEN LIFE mREFRESH TOKEN LIFE dYou can generate these secret keys in NodeJS console REPL Read Evaluate Print Loop using require crypto randomBytes toString base Because the access token is meant to be short lived It has been set to expire after minutes The refresh token is meant to remain valid for a longer duration so its expiration time has been set to days Adding Dummy DataFor the sake of simplicity I am not using any database in this article so let s create a new data js file inside the data folder This file contains the dummy data required for the application to function data jsconst users id name John Doe email johndoe example com userName johndoe password JohnDoe id name Jane Smith email janesmith example com userName janesmith password JaneSmith const tokens userId number refreshToken string expirationTime number module exports users tokens Here the users array is used to store the application s users and the tokens array is used to store the users refresh tokens along with their user ID and the token s expiration time Note ー I am storing the passwords as plain text but you should not store them as plain text for real world applications Adding Routes Controllers and MiddlewaresAdding Auth RoutesAdd this code to the auth js file inside the routes folder const router require express Router const authController require controllers auth const authMiddleware require middlewares auth router post sign up authController signUp authMiddleware generateAuthTokens router post login authController login authMiddleware generateAuthTokens router post logout authMiddleware isAuthenticated authController logout router post refresh authController refreshAccessToken module exports router POST auth sign up This endpoint handles the sign up requests It uses the authController signUp method to create a new user account and then uses the authMiddleware generateAuthTokens middleware to generate authentication tokens for the user POST auth login This endpoint handles the login requests It uses the authController login method to authenticate the user and then uses the authMiddleware generateAuthTokens middleware to generate authentication tokens for the user POST auth logout This endpoint handles user logout requests It uses the authMiddleware isAuthenticated middleware to check if the user is authenticated and then uses the authController logout method to log out the user POST auth refresh This endpoint is used to refresh the access token When the access token expires the client can use this endpoint to obtain a new access token by sending a valid refresh token in the request body The authController refreshAccessToken function is called to handle this request and generate a new access token Adding Users RoutesAdd this code to the users js file inside the routes folder const router require express Router const isAuthenticated require middlewares auth const usersController require controllers users router get list isAuthenticated usersController getUsersList router get me isAuthenticated usersController getAuthenticatedUser router get id isAuthenticated usersController getUserById module exports router GET users list This endpoint is used to retrieve the list of users It uses the authMiddleware isAuthenticated middleware to check if the user is authenticated and then uses the usersController getUsersList method to get the list of users GET users me This endpoint is used to retrieve the authenticated user s information It uses the authMiddleware isAuthenticated middleware to check if the user is authenticated and then uses the usersController getAuthenticatedUser method to get the authenticated user GET users id This endpoint is used to retrieve a user s information by ID It uses the authMiddleware isAuthenticated middleware to check if the user is authenticated and then uses the usersController getUserById method to get the user by their ID The user s ID is specified in the URL path using a route parameter id Updating app js Add this code inside app js to add the auth and users routes Existing Code const path require path require dotenv config const express require express const cors require cors const cookieParser require cookie parser New Code const authRoutes require routes auth const usersRoutes require routes users Existing Code const PORT NODE ENV process env const isDev NODE ENV development const app express if isDev app use cors origin http localhost optionsSuccessStatus credentials true app use express json type application json app use cookieParser process env COOKIE SECRET app use express static path join dirname public New Code app use api auth authRoutes app use api users usersRoutes Adding Auth ControllersAdd this code to the auth js file inside the controllers folder Sign up Controllerconst createError require http errors const users require data data const signUp async req res next gt const name username email password req body if name username email password return res status json error Please fill all the required fields try const userAlreadyExists users find user gt if user userName username user email email return true return false if userAlreadyExists return res status json error Username or email already exists const newUser id users users length id name name userName username email email password password users push newUser req userId newUser id return next catch error return next error module exports signUp The signUp function is responsible for handling the sign up process It requires the user s name username email and password to be sent in the request body It then checks if all the required fields are present and if not it returns a response with a status code and an error message Next it checks if a user with the same username or email already exists in the users array If it does it returns a response with a status code and an error message indicating that the username or email already exists If the user does not already exist the function creates a new user object with the required fields assigns it a unique id and pushes it to the users array The function then sets the userId property of the req object to the newly created user s id and calls the next function to pass control to the next middleware to generate the authentication tokens for the user If any error occurs during the execution of the function it calls the next function with the error to pass control to the error handling middleware Login Controllerconst createError require http errors const users require data data const signUp async req res next gt const login async req res next gt const username password req body try if username password return res status json error Please fill all the required fields const user users find user gt if user userName username user email username return true return false if user const error createError Unauthorized Invalid username or password throw error const passwordsMatch user password password if passwordsMatch const error createError Unauthorized Invalid username or password throw error req userId user id return next catch error return next error module exports signUp login The login function is responsible for handling the log in process It requires the user s username and password to be sent in the request body If either of these fields is missing it sends an error response back to the client indicating that both fields are required Next the function searches for a user in the users array by checking if either the userName or email of the user matches the provided username If a matching user is found the function checks if the provided password matches the user s password If the provided password does not match the function sends an error response indicating that the username or password is invalid If the provided password matches the function then sets the userId property of the req object to the authenticated user s id and calls the next function to pass control to the next middleware to generate the authentication tokens for the user If any error occurs during the execution of the function it calls the next function with the error to pass control to the error handling middleware Logout Controllerconst jwt require jsonwebtoken const createError require http errors const ms require ms const clearTokens generateJWT require utils auth const users tokens require data data const signUp async req res next gt const login async req res next gt const logout async req res next gt await clearTokens req res next return res sendStatus module exports signUp login logout The logout function is responsible for logging out the user It does so by calling the clearTokens function to remove the user s refresh token from the server as well as from the user s cookie Once the clearTokens function has finished its execution the logout function sends the response with the HTTP status code of which means No Content back to the client Refresh Access Token Controllerconst jwt require jsonwebtoken const createError require http errors const ms require ms const clearTokens generateJWT require utils auth const users tokens require data data const signUp async req res next gt const login async req res next gt const logout async req res next gt const refreshAccessToken async req res next gt const REFRESH TOKEN SECRET ACCESS TOKEN SECRET ACCESS TOKEN LIFE process env const signedCookies req const refreshToken signedCookies if refreshToken return res sendStatus try const refreshTokenInDB tokens find token gt token refreshToken refreshToken refreshToken if refreshTokenInDB await clearTokens req res next const error createError Unauthorized throw error try const decodedToken jwt verify refreshToken REFRESH TOKEN SECRET const userId decodedToken const user users find user gt user id userId if user await clearTokens req res const error createError Invalid credentials throw error const accessToken generateJWT user id ACCESS TOKEN SECRET ACCESS TOKEN LIFE return res status json user accessToken expiresAt new Date Date now ms ACCESS TOKEN LIFE catch error return next error catch error return next error module exports signUp login logout refreshAccessToken This refreshAccessToken function is responsible for refreshing the access token of a user The function first checks for a refresh token in the signed cookies of the request If a refresh token is found it checks if the token is valid by comparing it with the tokens stored in the tokens array If the token is invalid it clears all tokens and throws an error with a status code If the token is valid it decodes the refresh token to get the user ID checks if the user is valid generates a new access token and returns it along with the user information and the expiration time If there is an error in the process the function passes the error to the next error handling middleware function Adding Users ControllersAdd this code to the users js file inside the controllers folder const createError require http errors const users require data data const getUsersList async req res next gt const usersListWithOutPassword users map user gt const password userWithOutPassword user return userWithOutPassword return res status json data usersListWithOutPassword const getAuthenticatedUser async req res next gt try const userId req const authenticatedUser users find user gt user id userId if authenticatedUser return res status json data authenticatedUser const error createError NotFound throw error catch error return next error const getUserById async req res next gt try const id req params const user users find user gt user id id if user return res status json data user const error createError NotFound throw error catch error return next error module exports getUsersList getAuthenticatedUser getUserById getUsersList This function returns a list of all users getAuthenticatedUser This function returns the currently authenticated user based on their userId getUserById This function returns a user by their ID Adding Auth MiddlewaresAdd this code to the auth js file inside the middlewares folder generateAuthTokens middlewareThis middleware is used to generate access and refresh tokens once a user successfully signs up or logs into our application const jwt require jsonwebtoken const createError require http errors const ms require ms const generateJWT require utils auth const ACCESS TOKEN LIFE REFRESH TOKEN LIFE ACCESS TOKEN SECRET REFRESH TOKEN SECRET NODE ENV process env const dev NODE ENV development const users tokens require data data const generateAuthTokens async req res next gt try const user users find user gt user id req userId const refreshToken generateJWT req userId REFRESH TOKEN SECRET REFRESH TOKEN LIFE const accessToken generateJWT req userId ACCESS TOKEN SECRET ACCESS TOKEN LIFE const token refreshToken userId req userId expirationTime new Date Date now ms REFRESH TOKEN LIFE getTime tokens push token res cookie refreshToken refreshToken httpOnly true secure dev signed true expires new Date Date now ms REFRESH TOKEN LIFE const expiresAt new Date Date now ms ACCESS TOKEN LIFE return res status json user token accessToken expiresAt catch error return next error module exports generateAuthTokens The refresh and access tokens are generated by calling the generateJWT function with the authenticated user s ID token secret and the token expiration time Here I am sending the access token as part of the response body along with its expiration time and the authenticated user s object and sending the refresh token as an httpOnly cookie I am also saving the refresh token in the database tokens array here to invalidate the user s session from the backend Note ー I am sending the refresh token as an httpOnly cookie to prevent it from being read using JavaScript and setting the secure attribute to false in development mode and true in production to only send cookies using HTTPS in production isAuthenticated MiddlewareThis middleware is used to check if the user is authenticated to access the protected routes const jwt require jsonwebtoken const createError require http errors const ms require ms const generateJWT require utils auth const ACCESS TOKEN LIFE REFRESH TOKEN LIFE ACCESS TOKEN SECRET REFRESH TOKEN SECRET NODE ENV process env const dev NODE ENV development const users tokens require data data const generateAuthTokens async req res next gt const isAuthenticated async req res next gt try const authToken req get Authorization const accessToken authToken split Bearer if accessToken const error createError Unauthorized throw error const signedCookies req const refreshToken signedCookies if refreshToken const error createError Unauthorized throw error let refreshTokenInDB tokens find token gt token refreshToken refreshToken if refreshTokenInDB const error createError Unauthorized throw error refreshTokenInDB refreshTokenInDB refreshToken let decodedToken try decodedToken jwt verify accessToken ACCESS TOKEN SECRET catch err const error createError Unauthorized return next error const userId decodedToken const user users find user gt user id userId if user const error createError Unauthorized throw error req userId user id return next catch error return next error module exports generateAuthTokens isAuthenticated This middleware function checks whether the incoming request is authenticated or not It does this by first checking if the request has an access token in the authorization header If it doesn t the function throws an error indicating that the request is unauthorized If the request has an access token the middleware function checks for the presence of a refresh token in a signed cookie If there is no refresh token the function throws an error indicating that the request is unauthorized If the request has both an access token and a refresh token the middleware function checks whether the refresh token is present in the database If it is not the function throws an error indicating that the request is unauthorized If the refresh token is present in the database the middleware function attempts to decode the access token using the access token secret If the decoding fails the function throws an error indicating that the request is unauthorized If the decoding succeeds the middleware function retrieves the user ID from the decoded token and checks if there is a user in the database with that ID If there is no user the function throws an error indicating that the request is unauthorized If the user is found the middleware function sets the userId property of the request object to the user s ID and calls the next function to pass control to the next middleware function in the chain Adding Utility FunctionsAdd this code inside the auth js file inside the utils directory const jwt require jsonwebtoken const tokens require data data const dev process env NODE ENV development const generateJWT userId secret expirationTime gt return jwt sign userId secret expiresIn expirationTime const clearTokens async req res gt const signedCookies req const refreshToken signedCookies if refreshToken const index tokens findIndex token gt token refreshToken refreshToken if index tokens splice index res clearCookie refreshToken httpOnly true secure dev signed true module exports generateJWT clearTokens generateJWT This function is used to generate the access and refresh token using the jsonwebtoken library clearTokens This function is used clear the refresh token from the database and the cookie when a user logs out from the application Creating React ApplicationRun the following commands to initialize the React application and install the required dependencies cd refresh token auth appnpx create react app clientcd clientnpm install axios react router dom react hook formnpm install save dev sassFolder StructureBefore we start writing any code let s create the folder structure required for the front end application You can create the above directories with these commands cd client srcmkdir components contexts utils Optional Adding fonts and stylesAdd this font to the head section of the index html file under the public directory lt link href wght amp display swap rel stylesheet gt Replace the CSS code inside the index css with the code below before after margin padding box sizing border box font family inherit body margin font family Urbanist sans serif webkit font smoothing antialiased moz osx font smoothing grayscale And finally remove the code inside the App css file or delete the App css as we won t need this file in this tutorial Proxying API RequestsAdd this line of code to the package json file if you want to write requests like axios post api auth sign up instead of axios post http localhost api auth sign up proxy http localhost Signup ComponentLet s start by creating the signup component which allows users to sign up for our application by filling out the signup form Note ー We will use CSS modules to style our React application So for each component we will also create a CSS or SCSS file for that component Signup jsCreate a new folder Signup under the components directory and create a new file Signup js under that new folder import Link from react router dom import useForm from react hook form import styles from Signup module scss const Signup gt const handleSubmit register formState errors touchedFields useForm defaultValues name username email password confirmPassword mode onChange const onSubmit async values gt return lt div className styles container gt lt div className styles formWrapper gt lt form className styles form onSubmit handleSubmit onSubmit gt lt h className styles formTitle gt Create New Account lt h gt lt div className styles formGroup gt lt input className styles input type text name name id name placeholder Name register name required value true message Name is required minLength value message Name cannot be less than characters maxLength value message Name cannot be more than characters gt lt div className styles validationError gt lt span gt touchedFields name amp amp errors name message lt span gt lt div gt lt div gt lt div className styles formGroup gt lt input className styles input type text name username id username placeholder Username register username required value true message Username is required minLength value message Username cannot be less than characters gt lt div className styles validationError gt lt span gt touchedFields username amp amp errors username message lt span gt lt div gt lt div gt lt div className styles formGroup gt lt input className styles input type email name email id email autoComplete email placeholder Email register email required value true message Email is required pattern value a zA Z a zA Z a zA Z message Please enter a valid email gt lt div className styles validationError gt lt span gt touchedFields email amp amp errors email message lt span gt lt div gt lt div gt lt div className styles formGroup gt lt input className styles input type password name password id password autoComplete new password placeholder Password register password required value true message Password is required minLength value message Password cannot be less than characters maxLength value message Password cannot be more than characters gt lt div className styles validationError gt lt span gt touchedFields password amp amp errors password message lt span gt lt div gt lt div gt lt div className styles formGroup gt lt input className styles input type password name confirmPassword id confirmPassword autoComplete new password placeholder Confirm Password register confirmPassword required value true message confirmPassword is required validate value formValues gt if value formValues password return Confirm password does not match the password return true gt lt div className styles validationError gt lt span gt touchedFields confirmPassword amp amp errors confirmPassword message lt span gt lt div gt lt div gt lt div className styles formGroup gt lt button className styles submitButton type submit gt Sign Up lt button gt lt div gt lt p className styles text gt lt span gt Already have an account lt span gt lt Link className styles link to login gt Login lt Link gt lt p gt lt form gt lt div gt lt div gt export default Signup It s just a simple sign up form that contains name username email password and confirm password input fields using which a user can sign up for our application Note ー Here I am using the React Hook Form library to manage the sign up form You can use the HTML form validation to validate the form if you don t want to use any external library Signup module scssAdd this code inside the Signup module scss under the Signup folder to style the sign up form container display flex justify content center background color rgb padding px px min height vh formWrapper display flex justify content center box sizing border box align items center width form padding px px width px background fff box shadow px px px px rgb margin right px media max width px width formTitle color teal font weight text align left margin bottom px font size px media max width px font size px formGroup position relative margin px input font size px padding px px width outline px solid ddd border none color cf caret color teal font weight amp focus outline px solid teal media max width px font size px media max width px font size px submitButton background teal color white border px solid transparent padding px px font size px text transform uppercase cursor pointer validationError color red height px text color b font weight media max width px font size px media max width px font size px link color teal margin left px Adding the Sign up RouteReplace the code inside the App js file with the code below import createBrowserRouter RouterProvider from react router dom import Signup from components Signup Signup function App const router createBrowserRouter path element lt h gt Hello World lt h gt path sign up element lt Signup gt return lt div className App gt lt RouterProvider router router gt lt div gt export default App You can now visit the sign up page by going to http localhost sign upMaking the Form WorkSo we have made the sign up form but the users can t actually sign up through it Let s connect the form with the backend which allows users to sign up if they haven t already Saving Authentication State Using Context APIBefore we connect our form with the backend let s create a context to store the currently authenticated user auth context jsAdd this file under the src contexts directory and add the following code to that file import as React from react import PropTypes from prop types import STATUS from utils utils const initialState user token null expiresAt null isAuthenticated false status STATUS PENDING const AuthContext React createContext initialState login user token expiresAt gt logout gt updateUser gt setAuthenticationStatus gt const authReducer state action gt switch action type case login return user action payload user token action payload token expiresAt action payload expiresAt isAuthenticated true verifyingToken false status STATUS SUCCEEDED case logout return initialState status STATUS IDLE case updateUser return state user action payload user case status return state status action payload status default throw new Error Unhandled action type action type const AuthProvider children gt const state dispatch React useReducer authReducer initialState const login React useCallback user token expiresAt gt dispatch type login payload user token expiresAt const logout React useCallback gt dispatch type logout const updateUser React useCallback user gt dispatch type updateUser payload user const setAuthenticationStatus React useCallback status gt dispatch type status payload status const value React useMemo gt state login logout updateUser setAuthenticationStatus state setAuthenticationStatus login logout updateUser return lt AuthContext Provider value value gt children lt AuthContext Provider gt const useAuth gt const context React useContext AuthContext if context undefined throw new Error useAuth must be used within a AuthProvider return context AuthProvider propTypes children PropTypes element isRequired export AuthProvider useAuth In this code I am using a custom hook useAuth which returns the current context value created using the AuthContext which contains the authentication state along with the functions used to log in log out and update the authentication status I am also defining a component AuthProvider that returns the context provider AuthContext Provider The AuthProvider component uses the useReducer hook to update the authentication state whenever a user logs in or logs out of the application The state returned by the useReducer is then passed as the value along with functions like login and logout which updates the auth state using the dispatch method returned by the useReducer hook to the AuthContext Provider The AuthContext Provider also contains components passed to the AuthProvider component as children utils jsAdd this code inside the src utils utils js file const STATUS Object freeze IDLE idle PENDING pending SUCCEEDED succeeded FAILED failed export STATUS This code defines an object which is used to represent the status of an HTTP request whether it is pending failed or succeeded Using the AuthProviderReplace the code inside the src index js file with the code below import React from react import ReactDOM from react dom client import index css import App from App import reportWebVitals from reportWebVitals import AuthProvider from contexts auth context const root ReactDOM createRoot document getElementById root root render lt React StrictMode gt lt AuthProvider gt lt App gt lt AuthProvider gt lt React StrictMode gt If you want to start measuring performance in your app pass a function to log results for example reportWebVitals console log or send to an analytics endpoint Learn more reportWebVitals Using this code every component nested deep inside the lt App gt component can now access and update the authentication state using the useAuth custom hook Connecting the form with the backendUpdate the code inside the Signup js file with the code below import Link useNavigate from react router dom import useForm from react hook form import axios from axios import useAuth from contexts auth context import STATUS from utils utils import styles from Signup module scss const Signup gt Existing code const handleSubmit register formState errors touchedFields useForm defaultValues name username email password confirmPassword mode onChange New code const navigate useNavigate const login setAuthenticationStatus useAuth const onSubmit async values gt const newUser name values name username values username email values email password values password confirmPassword values confirmPassword try setAuthenticationStatus STATUS PENDING const response await axios post api auth sign up newUser setAuthenticationStatus STATUS SUCCEEDED const user token expiresAt response data login user token expiresAt navigate catch error alert error response data error message setAuthenticationStatus STATUS FAILED Existing code return lt div className styles container gt lt div className styles formWrapper gt lt form className styles form onSubmit handleSubmit onSubmit gt lt h className styles formTitle gt Create New Account lt h gt lt div className styles formGroup gt lt input className styles input type text name name id name placeholder Name register name required value true message Name is required minLength value message Name cannot be less than characters maxLength value message Name cannot be more than characters gt lt div className styles validationError gt lt span gt touchedFields name amp amp errors name message lt span gt lt div gt lt div gt lt div className styles formGroup gt lt input className styles input type text name username id username placeholder Username register username required value true message Username is required minLength value message Username cannot be less than characters gt lt div className styles validationError gt lt span gt touchedFields username amp amp errors username message lt span gt lt div gt lt div gt lt div className styles formGroup gt lt input className styles input type email name email id email autoComplete email placeholder Email register email required value true message Email is required pattern value a zA Z a zA Z a zA Z message Please enter a valid email gt lt div className styles validationError gt lt span gt touchedFields email amp amp errors email message lt span gt lt div gt lt div gt lt div className styles formGroup gt lt input className styles input type password name password id password autoComplete new password placeholder Password register password required value true message Password is required minLength value message Password cannot be less than characters maxLength value message Password cannot be more than characters gt lt div className styles validationError gt lt span gt touchedFields password amp amp errors password message lt span gt lt div gt lt div gt lt div className styles formGroup gt lt input className styles input type password name confirmPassword id confirmPassword autoComplete new password placeholder Confirm Password register confirmPassword required value true message confirmPassword is required validate value formValues gt if value formValues password return Confirm password does not match the password return true gt lt div className styles validationError gt lt span gt touchedFields confirmPassword amp amp errors confirmPassword message lt span gt lt div gt lt div gt lt div className styles formGroup gt lt button className styles submitButton type submit gt Sign Up lt button gt lt div gt lt p className styles text gt lt span gt Already have an account lt span gt lt Link className styles link to login gt Login lt Link gt lt p gt lt form gt lt div gt lt div gt export default Signup The onSubmit method is called when the user submits the signup form Inside the function a new object called newUser is created with its properties set to form values Inside the try catch block we call the signup API with the newUser object as the request body If the request is successful we extract the user token and the token expiry time from the response and call the login function from the useAuth hook This function updates the authentication state with the new user and token and redirects the user to the home page Login ComponentLogin jsAdd this code inside the Login js file under the src components Login directory import Link useNavigate from react router dom import useForm from react hook form import axios from axios import useAuth from contexts auth context import STATUS from utils utils import styles from Login module scss const Login gt const handleSubmit register formState errors touchedFields useForm defaultValues username password mode onChange const navigate useNavigate const login setAuthenticationStatus useAuth const onSubmit async values gt const user username values username password values password try setAuthenticationStatus STATUS PENDING const response await axios post api auth login user setAuthenticationStatus STATUS SUCCEEDED const user userObj token expiresAt response data login userObj token expiresAt navigate catch error alert error response data error message return lt div className styles container gt lt div className styles formWrapper gt lt form className styles form onSubmit handleSubmit onSubmit gt lt h className styles formTitle gt Sign In lt h gt lt div className styles formGroup gt lt input className styles input type text name username id username aria label Username or Email required placeholder Username or Email register username required value true message This field is required gt lt div className styles validationError gt lt span gt touchedFields name amp amp errors name message lt span gt lt div gt lt div gt lt div className styles formGroup gt lt input className styles input type password name password id password required placeholder Password register password required value true message Password is required gt lt div className styles validationError gt lt span gt touchedFields password amp amp errors password message lt span gt lt div gt lt div gt lt div className styles formGroup gt lt button className styles submitButton type submit gt Sign In lt button gt lt div gt lt p className styles text gt lt span gt Don t have an account lt span gt lt Link className styles link to sign up gt Sign Up lt Link gt lt p gt lt form gt lt div gt lt div gt export default Login Login module scssAdd this code inside the Login module scss file under the src components Login directory container min height vh background color rgb display flex justify content center align items center padding px px formWrapper max width px width form background color fff box shadow px px px px rgb width padding px px formTitle color teal font weight text align left margin bottom px font size px formGroup position relative margin px input font size px padding px px width outline px solid ddd border none color cf caret color teal font weight amp focus outline px solid teal media max width px font size px media max width px font size px submitButton background teal color white border px solid transparent padding px px font size px text transform uppercase cursor pointer disabled background color grey validationError color red height px text color b font weight media max width px font size px media max width px font size px link color teal margin left px Adding the Login RouteReplace the code inside the App js file with the code below import createBrowserRouter RouterProvider from react router dom import Signup from components Signup Signup import Login from components Login Login function App const router createBrowserRouter path element lt h gt Hello World lt h gt path sign up element lt Signup gt path login element lt Login gt return lt div className App gt lt RouterProvider router router gt lt div gt export default App You can now visit the login page by going to http localhost loginAdding Silent AuthenticationAs we know the access token is only valid for minutes without silent authentication the user will have to log in again every time the token expires To prevent users from getting logged out every time the token expires let s implement silent authentication What is Silent Authentication Silent Authentication is the process of refreshing the user s access token in the background before the token expires or when a user reloads the page Because we are not storing access tokens in local storage to prevent XSS attacks we have to perform silent authentication on page reload as well Replace the code inside the App js with the code below import useCallback useEffect from react import createBrowserRouter RouterProvider from react router dom import axios from axios import Signup from components Signup Signup import Login from components Login Login import useAuth from contexts auth context function App New Code const login logout isAuthenticated expiresAt useAuth const refreshAccessToken useCallback async gt try const response await axios post api auth refresh withCredentials true const user accessToken expiresAt response data if response status logout else login user accessToken expiresAt catch error logout login logout useEffect gt refreshAccessToken refreshAccessToken useEffect gt let refreshAccessTokenTimerId if isAuthenticated refreshAccessTokenTimerId setTimeout gt refreshAccessToken new Date expiresAt getTime Date now return gt if isAuthenticated amp amp refreshAccessTokenTimerId clearTimeout refreshAccessTokenTimerId expiresAt isAuthenticated refreshAccessToken Existing code const router createBrowserRouter path element lt h gt Hello World lt h gt path sign up element lt Signup gt path login element lt Login gt return lt div className App gt lt RouterProvider router router gt lt div gt export default App So What s happening here Let s break down the code and explain its functionality step by step refreshAccessToken function This function is responsible for refreshing the access token It does so by making a POST request to api auth refresh endpoint Since the refresh token is stored as an httpOnly cookie I am also setting the withCredentials option to true to automatically send the refresh token with the request If the request is successful we call the login function to update the access token stored in memory otherwise we log out the user if there s any error Performing silent authentication on page reload Since the access token is stored only in the memory and not in local storage or cookie we have to perform silent authentication whenever the page reloads or the application is loaded for the first time We do this by calling the refreshAccessToken function inside the first useEffect hook that only runs when the App component is mounted Performing silent authentication before the access token expires The second useEffect is responsible for performing silent authentication before the access token expires This effect runs whenever a user signs up or logs in to the application or when the access token is refreshed Inside this effect we first check if the user is authenticated if yes then we set a timer using the setTimeout which executes the refreshAccessToken function seconds before the access token expires We clear the timer when the effect cleanup is run Adding additional routes and componentsA user is now able to sign up and log in to our application and can remain logged in as long as the refresh token is valid Let s add some more routes and components which a user can only access when they are authenticated Adding Home ComponentAdd this code inside the Home js file under the src components Home directory import useAuth from contexts auth context import styles from Home module scss const Home gt const user useAuth return lt div className styles container gt lt h className styles heading gt lt span className styles colorTeal gt Welcome lt span gt lt span className styles colorBlack gt user name lt span gt lt h gt lt div gt export default Home This is just a simple home page where we print the currently authenticated user s name on the screen Home module scssAdd this code inside the Home module scss file under the src components Home directory container margin top px padding px heading text align center colorTeal color teal colorBlack color b Adding Users ComponentAdd this code inside the Users js file under the src components Users directory import useEffect useState from react import axios from axios import User from User User import useAuth from contexts auth context import styles from Users module scss const Users gt const token useAuth const users setUsers useState useEffect gt axios get api users list headers Authorization Bearer token then res gt setUsers res data data catch error gt console log Something went wrong error token return lt div className styles container gt users map user gt lt div key user id className styles userContainer gt lt User user user gt lt div gt lt div gt export default Users In this component we first fetch the list of users using an HTTP GET request to the api users list endpoint passing the access token as an Authorization header If the request is successful we set users state with the user list received from the server Users module scssAdd this code inside the Users module scss file under the src components Users directory container margin top px userContainer margin bottom px Adding User ComponentAdd this code inside the User js file under the src components Users User directory import styles from User module scss const User user gt return lt div className styles container gt lt div className styles imageContainer gt lt img className styles image src alt User Avatar gt lt div gt lt div gt lt h gt user name lt h gt lt p gt Lorem ipsum dolor sit amet consectetur adipiscing elit Integer ornare neque quis purus tempus interdum Lorem ipsum dolor sit amet consectetur adipiscing elit lt p gt lt div gt lt div gt export default User User module scssAdd this code inside the User module scss file under the src components Users User directory container display flex max width px margin auto gap px align items center box shadow px px rgba padding px px imageContainer width px height px overflow hidden flex basis px flex shrink flex grow border radius image width height object fit cover Adding routes for Home and Users componentsUpdate the router config in App js with the new config import useCallback useEffect from react import createBrowserRouter RouterProvider from react router dom import axios from axios import Signup from components Signup Signup import Login from components Login Login import Home from components Home Home import Users from components Users Users import useAuth from contexts auth context function App const login logout isAuthenticated expiresAt useAuth const refreshAccessToken useCallback async gt try const response await axios post api auth refresh withCredentials true const user accessToken expiresAt response data if response status logout else login user accessToken expiresAt catch error logout login logout useEffect gt refreshAccessToken refreshAccessToken useEffect gt let refreshAccessTokenTimerId if isAuthenticated refreshAccessTokenTimerId setTimeout gt refreshAccessToken new Date expiresAt getTime Date now return gt if isAuthenticated amp amp refreshAccessTokenTimerId clearTimeout refreshAccessTokenTimerId expiresAt isAuthenticated refreshAccessToken New code const router createBrowserRouter path element lt Home gt path sign up element lt Signup gt path login element lt Login gt path users element lt Users gt Existing code return lt div className App gt lt RouterProvider router router gt lt div gt export default App You can now visit the home and users page by going to http localhost and http localhost usersHome pageUsers PageAdding NavbarLet s add a Navbar component that displays Login and Sign up links when the user is not logged in and displays the logout button when a user is logged in Navbar jsAdd this code inside the Navbar js under the src components Navbar directory import Link useNavigate from react router dom import axios from axios import useAuth from contexts auth context import styles from Navbar module scss const Navbar gt const isAuthenticated token logout useAuth const navigate useNavigate const logOutHandler async gt try await axios post api auth logout headers Authorization Bearer token logout navigate login catch error console log Something went wrong error return lt header className styles header gt lt nav className styles navigation gt lt div gt lt Link className styles brand to gt Demo App lt Link gt lt div gt lt div className styles navigationListContainer gt lt ul className styles navigationList gt isAuthenticated amp amp lt gt lt li className styles navigationItem gt lt Link className styles navigationLink to login gt Login lt Link gt lt li gt lt li className styles navigationItem gt lt Link className styles navigationLink to sign up gt Sign Up lt Link gt lt li gt lt gt isAuthenticated amp amp lt gt lt li className styles navigationItem gt lt Link className styles navigationLink to users gt Users lt Link gt lt li gt lt li className styles navigationItem gt lt button className styles navigationLink onClick logOutHandler gt Log out lt button gt lt li gt lt gt lt ul gt lt div gt lt nav gt lt header gt export default Navbar There are a couple of things happening here let me explain them step by step Since we are using the useAuth custom hook to handle user authentication it provides us with a set of properties and functions to effectively manage the authentication process The isAuthenticated property is used to check if the user is authenticated or not If the user is authenticated we show the log out button otherwise we display the login and sign up buttons The logOutHandler is called when a user clicks on the log out button It sends a POST request to api auth logout endpoint with the access token as the Authorization header and calls the logout function once we get a successful response back from the server The logout is responsible for clearing the user object from the reducer state After the user is logged out we redirect them to the login page Navbar module scssAdd this code inside the Navbar module scss file under the src components Navbar directory header height px width background color white display flex align items center padding px webkit box shadow px px px px rgba moz box shadow px px px px rgba box shadow px px px px rgba position fixed top left right z index media max width px height px navigation display flex align items center justify content space between flex brand color b text decoration none font size px font weight text transform uppercase amp hover color teal media max width px font size px navigationList display flex align items center justify content flex end list style none flex basis media max width px flex direction column navigationItem margin right px transition all s media max width px margin right margin bottom px navigationLink display flex flex direction column align items center justify content center color b cursor pointer text transform uppercase text decoration none font size px amp hover color teal amp hover svg stroke teal amp hover gt span color teal button styles background none border none media max width px flex direction row amp svg margin right px Adding Navbar to the applicationWe have two choices when it comes to adding the Navbar component to our application First we can add it separately to each component like the Login Signup or Home page Alternatively we can use the Layout route and component which allows us to group multiple routes together under a common layout Adding Layout route and componentLayout jsAdd this code inside the Layout js file under the src components Layout directory import Outlet from react router dom import Navbar from Navbar Navbar const Layout gt return lt div gt lt Navbar gt lt div gt lt Outlet gt lt div gt lt div gt export default Layout Here we are using React Router s lt Outlet gt component to render the child route components inside of the Layout component Optional Adding Route ProtectionCurrently a user can visit the Home and Users page even if they are unauthenticated Similarly if a user is already authenticated they can still visit the Login and Sign Up pages To prevent that let s add route protection Update the App js code with this code import useCallback useEffect from react import createBrowserRouter RouterProvider useLocation Navigate from react router dom import PropTypes from prop types import axios from axios import Signup from components Signup Signup import Login from components Login Login import Home from components Home Home import Users from components Users Users import Layout from components Layout Layout import SplashScreen from components SplashScreen SplashScreen import useAuth from contexts auth context import STATUS from utils utils function App const login logout isAuthenticated expiresAt useAuth const refreshAccessToken useCallback async gt try const response await axios post api auth refresh withCredentials true const user accessToken expiresAt response data if response status logout else login user accessToken expiresAt catch error logout login logout useEffect gt refreshAccessToken refreshAccessToken useEffect gt let refreshAccessTokenTimerId if isAuthenticated refreshAccessTokenTimerId setTimeout gt refreshAccessToken new Date expiresAt getTime Date now return gt if isAuthenticated amp amp refreshAccessTokenTimerId clearTimeout refreshAccessTokenTimerId expiresAt isAuthenticated refreshAccessToken New code const router createBrowserRouter element lt Layout gt children path element lt RequireAuth redirectTo sign up gt lt Home gt lt RequireAuth gt path sign up element lt RedirectIfLoggedIn redirectTo gt lt Signup gt lt RedirectIfLoggedIn gt path login element lt RedirectIfLoggedIn redirectTo gt lt Login gt lt RedirectIfLoggedIn gt path users element lt RequireAuth redirectTo sign up gt lt Users gt lt RequireAuth gt return lt div className App gt lt RouterProvider router router gt lt div gt New codeconst RequireAuth children redirectTo gt const isAuthenticated status useAuth const location useLocation if status STATUS PENDING return lt SplashScreen gt return isAuthenticated children lt Navigate to redirectTo state from location gt New codeconst RedirectIfLoggedIn children redirectTo gt const isAuthenticated status useAuth const location useLocation if status STATUS PENDING return lt SplashScreen gt return isAuthenticated lt Navigate to location state from pathname redirectTo gt children RequireAuth propTypes children PropTypes element isRequired redirectTo PropTypes string isRequired RedirectIfLoggedIn propTypes children PropTypes element isRequired redirectTo PropTypes string isRequired export default App We have added two new components to the App js file lt RequireAuth gt and lt RedirectIfLoggedIn gt component The RequireAuth component is used to protect routes that only an authenticated user can visit while the RedirectIfLoggedIn component is used to hide routes like sign up and login which an authenticated user cannot visit RequireAuth Component This component takes in two props children and redirectTo The redirectTo prop specifies the path to which an unauthenticated user should be redirected It relies on the isAuthenticated and status properties returned by the useAuth hook to determine the user s authentication status If the user is unauthenticated the component redirects them to the path specified in the redirectTo prop On the other hand if the user is authenticated the component renders the child components passed through the children prop If the authentication status is pending the component displays the SplashScreen component RedirectIfLoggedIn Component This component also takes in two props children and redirectTo The redirectTo prop specifies the path to which an authenticated user should be redirected It relies on the isAuthenticated and status properties returned by the useAuth hook to determine the user s authentication status If the user is authenticated the component redirects them to the path specified in the redirectTo prop On the other hand if the user is unauthenticated the component renders the child components passed through the children prop If the authentication status is pending the component displays the SplashScreen component SplashScreen Component Add this code inside the SplashScreen js file under the src components SplashScreen directory import styles from SplashScreen module scss const SplashScreen gt return lt div className styles container gt lt div className styles iconContainer gt lt div gt loading lt div gt lt div gt lt div gt export default SplashScreen SplashScreen module scssAdd this code inside the SplashScreen module scss file under the src components SplashScreen directory container background color fff color teal position fixed top left height width z index iconContainer position absolute top left translate color teal Final Result Source CodeYou can download the source code from my GitHub repo SukhjinderArora refresh token auth app Refresh and access token based authentication in React and Node js React and NodeJS Authentication with Refresh amp Access Tokens A Step by Step GuideLearn How to implement refresh and access token based authentication in React and Node jsDevelopment WorkflowRun the following commands to run this application locally on your system cd servernpm installnpm startcd clientnpm installnpm startYou can read the full article at View on GitHub ConclusionSo we have learned how to implement refresh and access token based authentication in React and NodeJS We have learned the difference between access and refresh tokens and how to perform silent authentication by refreshing access tokens in the background We have also learned how to protect routes in React applications using React Router That s it and hope you found this article helpful Please feel free to comment below and ask anything suggest feedback or just chat You can also follow me on Hashnode Medium and Twitter Cheers ️ 2023-05-30 16:13:17
海外TECH DEV Community From Zero To Hero: Front End Development Projects For Beginners[With Source Code] https://dev.to/husayn01/from-zero-to-hero-front-end-development-projects-for-beginnerswith-source-code-5mo From Zero To Hero Front End Development Projects For Beginners With Source Code Welcome fellow developers to today s blog post where we will explore the world of simple web development projects that are ideal for beginners Regardless of your age or technical background these projects provide a playground for aspiring coders to grow their abilities and embark on a path to becoming a skilled programmer The Power of Building Front End Projects Building projects is akin to playing the stock market It requires an investment of time and effort and while success is not guaranteed the process serves as a valuable learning experience Building projects is a lot like embarking on a thrilling adventure It requires dedication effort and a willingness to step outside of your comfort zone However the rewards that come from building front end projects are immeasurable When you engage in building front end projects you are actively applying the knowledge you ve acquired By putting theory into practice you solidify your understanding of concepts and develop problem solving skills Each project becomes an opportunity to explore new techniques experiment with different approaches and overcome challenges The beauty of front end projects lies in their versatility You have the freedom to choose projects that align with your interests allowing you to create something meaningful and engaging Whether it s building a personal portfolio website crafting a responsive landing page or developing a dynamic JavaScript calculator each project serves as a stepping stone on your journey to becoming a front end development hero Building projects not only helps you refine your technical skills but it also nurtures your creativity As you tackle design decisions implement interactive features and polish the user experience you gain a deeper appreciation for the artistry behind web development It s an opportunity to showcase your unique style and leave a lasting impression on your audience Beginner Projects for front end DevelopersNow let s dive into the heart of the matterーthe beginner projects that are both enjoyable and straightforward suitable even for those with limited coding experience These projects provide an opportunity to grasp essential front end development concepts while making the learning process delightful Project Simple websitePrerequisites To build a simple website you ll need the following prerequisites HTML Understanding of HTML tags and structure to create the content and layout of the website CSS Familiarity with CSS selectors styles and layout techniques to design and customize the website s appearance Basic Web Design Principles Knowledge of fundamental web design principles including visual hierarchy typography color theory and user experience Description Building a simple website involves creating a digital presence to showcase information products or services in an accessible and user friendly manner Here s a breakdown of how you can approach building a simple website Planning and Content Start by planning the purpose and goals of your website Determine the target audience and define the content that you want to present to visitors This could include text images videos or other multimedia elements HTML Structure Create the basic HTML structure for your website Use HTML tags to define headings paragraphs lists links images and other content elements Structure the content using semantic HTML for better accessibility and search engine optimization CSS Styling Apply CSS styles to enhance the visual appearance of your website Use CSS selectors to target HTML elements and apply colors fonts spacing and other visual properties Create a cohesive design by considering typography layout and consistent styling across the website Layout and Navigation Design the layout of your website to ensure a clear and intuitive user experience Organize the content into logical sections and create a navigation menu to allow visitors to navigate between different pages or sections of your site Consider using responsive design techniques to make your website mobile friendly Interactive Elements Enhance user engagement by incorporating interactive elements into your website This can include contact forms image sliders buttons accordions or other interactive components that provide a dynamic and engaging experience for visitors Testing and Optimization Test your website across different browsers and devices to ensure it displays correctly and functions properly Optimize your website s performance by minimizing file sizes optimizing images and utilizing caching techniques Test for accessibility to ensure your website is usable by people with disabilities Deployment and Domain Choose a hosting provider and deploy your website to make it accessible on the internet If you cannot afford to pay for a hosting plan you can use vercel or netlify They offer free hosting Live DemoSource code Project Quote generatorPrerequisites Basic knowledge of HTML CSS and JavaScript Familiarity with HTML tags CSS selectors and JavaScript functions Understanding of DOM manipulation and event handling in JavaScript Text editor or Integrated Development Environment IDE for coding Web browser for testing and previewing the project Description The quote generator project involves creating a web application that displays random quotes to the user when a button is clicked It s a great project for beginners to practice their HTML CSS and JavaScript skills while learning about event handling and dynamic content manipulation The project can be divided into the following steps HTML Structure Begin by setting up the HTML structure Create a container element to hold the quote and a button for generating new quotes Add appropriate IDs or classes to the necessary elements for easy access using JavaScript CSS Styling Apply CSS styling to make the quote generator visually appealing Customize the font colors and layout to match your desired design You can experiment with different CSS properties to achieve the desired look and feel JavaScript Functionality Write JavaScript code to handle the button click event and generate random quotes Define an array or object to store a collection of quotes When the button is clicked randomly select a quote from the collection and display it on the web page Dynamic Content Update Use JavaScript to update the quote content dynamically Access the necessary HTML elements using selectors or IDs and modify their text or innerHTML property with the selected quote Optional Additional Features Once you have the basic functionality working you can enhance the quote generator with additional features For example you can add a Share button to allow users to share quotes on social media include animations for a more interactive experience or provide the ability to filter quotes based on categories Throughout the project test your code in a web browser to ensure everything is functioning as expected You can also customize the project by adding your own styling or modifying the functionality to suit your preferences Live DemoSource code Project Password GeneratorPrerequisites To build a password generator you should have a basic understanding of the following HTML Knowledge of HTML is necessary to create the user interface elements such as input fields buttons and display areas CSS Familiarity with CSS will enable you to style the user interface and make it visually appealing JavaScript Proficiency in JavaScript is essential as it will be used to generate random passwords handle user interactions and manipulate the DOM to update the password display Description A password generator is a tool that creates random and secure passwords based on certain criteria Here s a breakdown of how a password generator can be built HTML Structure Start by creating the necessary HTML structure to display the password generator interface This typically includes input fields for specifying password length check boxes for selecting character types e g uppercase letters lowercase letters numbers symbols a button to generate the password and an area to display the generated password JavaScript Functionality Write a function that generates the password based on the user s specified criteria This function will typically include the logic to randomly select characters from the desired character types and combine them to form the password Handle user interactions such as retrieving the selected options password length and character types from the HTML elements and passing them to the password generation function Update the DOM to display the generated password in the designated area Randomization and Secure Passwords Utilize JavaScript s random number generation capabilities to ensure the password generated is random and secure Consider using built in functions like Math random and array manipulation methods to randomly select characters from the chosen character types Optional Features Allow users to customize the password criteria further such as setting a minimum requirement for each character type or excluding certain characters Implement additional functionalities like a Copy to Clipboard button to make it easier for users to use the generated password Live DemoSource code Project Analog ClockTo build an analog clock you ll need the following prerequisites Basic HTML Familiarity with HTML tags and structure Basic CSS Understanding of CSS selectors positioning and transformations Basic JavaScript Knowledge of JavaScript functions intervals and DOM manipulation Description Building an analog clock involves creating a visual representation of the current time using HTML CSS and JavaScript Here s a breakdown of how you can approach building an analog clock HTML Structure Start by creating the basic HTML structure for the clock Typically this would include a container element for the clock and nested elements for the clock face hour hand minute hand and second hand CSS Styling Apply CSS styles to position and style the clock elements Use CSS properties like position transform and border radius to create the circular clock face and hands Adjust the size colors and styling to achieve the desired visual appearance JavaScript Logic Write JavaScript code to update the position of the clock hands based on the current time Use JavaScript s Date object to get the current time and calculate the corresponding angles for the hour minute and second hands Update the CSS transform property of each hand to rotate them accordingly Clock Animation To make the clock continuously update and display the correct time use JavaScript s setInterval function to repeatedly call a function that updates the clock hands By specifying an appropriate interval e g every second the clock will continuously update to reflect the current time Responsive Design Consider making the analog clock responsive by using CSS media queries Adjust the size and layout of the clock elements for different screen sizes to ensure it displays well on various devices Live DemoSource code Project StopwatchPrerequisites To build a stopwatch using JavaScript you ll need the following prerequisites HTML Understanding of HTML tags and structure to create the stopwatch display and UI elements CSS Familiarity with CSS selectors styles and layout techniques to design and customize the stopwatch s appearance JavaScript Knowledge of JavaScript functions DOM manipulation and event handling Description Building a stopwatch involves creating a functional timer that can measure elapsed time accurately Here s a breakdown of how you can approach building a stopwatch using JavaScript HTML Structure Create the HTML structure for your stopwatch Use HTML tags to define the stopwatch display control buttons and other necessary elements Structure the layout using appropriate HTML elements and classes CSS Styling Apply CSS styles to enhance the visual appearance of your stopwatch Use CSS to customize the colors fonts and layout of the stopwatch interface Apply styles to the display area control buttons and other elements to create a visually appealing design JavaScript Logic Write JavaScript code to handle the stopwatch s functionality Implement functions to start stop and reset the stopwatch Use JavaScript s setInterval and clearInterval methods to measure elapsed time accurately and update the display accordingly Button Interactivity Add event listeners to the control buttons to capture user input When the start button is clicked start the stopwatch timer by invoking the appropriate functions Similarly clicking the stop button should pause the timer and the reset button should reset the timer to zero Time Calculation Use JavaScript s Date object or the performance now method to measure elapsed time accurately Calculate the time difference between the start and stop events and update the stopwatch display accordingly Display Formatting Format the stopwatch display to show the elapsed time in a user friendly manner Convert milliseconds to hours minutes seconds and milliseconds as needed Ensure that the display format is consistent and easy to read Responsive Design Consider implementing responsive design techniques to ensure your stopwatch functions well on different screen sizes and devices Use CSS media queries to adjust the layout and styling for optimal user experience Testing and Refinement Test your stopwatch thoroughly checking for accurate timekeeping and proper display Debug any issues or errors that may arise during testing Refine the design and functionality based on user feedback and testing results Live DemoSource code Project Simple Javascript calculatorPrerequisites To build a simple JavaScript calculator you ll need the following prerequisites HTML Understanding of HTML tags and structure to create the calculator interface CSS Familiarity with CSS selectors styles and layout techniques to design and customize the calculator s appearance JavaScript Knowledge of JavaScript functions DOM manipulation and event handling Description Building a simple JavaScript calculator involves creating a functional calculator interface that can perform basic arithmetic operations Here s a breakdown of how you can approach building a simple JavaScript calculator HTML Structure Create the HTML structure for your calculator Use HTML tags to define the calculator display buttons and other necessary elements Structure the layout using appropriate HTML elements and classes CSS Styling Apply CSS styles to enhance the visual appearance of your calculator Use CSS to customize the colors fonts and layout of the calculator interface Apply styles to the buttons display area and other elements to create an appealing design JavaScript Logic Write JavaScript code to handle the calculator s functionality Implement functions to perform arithmetic operations handle user input and update the display accordingly Use JavaScript s addEventListener method to handle button clicks and trigger the appropriate actions Button Interactivity Add event listeners to the calculator buttons to capture user input When a button is clicked retrieve the button value and perform the corresponding operation or update the display accordingly Use JavaScript to handle decimal numbers clear the display or evaluate the final result Responsive Design Consider implementing responsive design techniques to ensure your calculator functions well on different screen sizes and devices Use CSS media queries to adjust the layout and styling for optimal user experience Testing and Refinement Test your calculator thoroughly checking for accurate calculations and proper display Debug any issues or errors that may arise during testing Refine the design and functionality based on user feedback and testing results Live DemoSource code Project Tic Tac Toe GamePrerequisites To build a Tic Tac Toe game you ll need the following prerequisites HTML Familiarity with HTML tags and structure to create the game board and UI elements CSS Understanding of CSS selectors styles and layout to visually design the game JavaScript Knowledge of JavaScript functions arrays DOM manipulation and event handling Description Building a Tic Tac Toe game involves creating a playable game board where two players take turns marking X and O symbols until one of them wins or the game ends in a draw Here s a breakdown of how you can approach building a Tic Tac Toe game HTML Structure Begin by creating the basic HTML structure for the game board Use a combination of elements or an HTML table to represent the grid of cells for the Tic Tac Toe board CSS Styling Apply CSS styles to visually design the game board and UI elements Use CSS to set the dimensions of the cells customize the appearance of X and O symbols and style the game status display JavaScript Logic Write JavaScript code to handle the game logic Create data structures to represent the game board state track player turns and handle win conditions Implement functions to update the board check for a winning combination and determine the game s outcome User Interaction Add event listeners to the game cells to handle player moves When a player clicks on an empty cell update the board state display the corresponding symbol and check for a win or draw Allow players to take turns until the game is won or ends in a draw Game Outcome Display Implement a display mechanism to show the game outcome Update the UI to inform players when someone wins the game ends in a draw or it s the next player s turn Optionally provide a restart button to allow players to play again Optional Enhancements You can further enhance the game by adding features like player names score tracking a timer or an AI opponent for single player mode These enhancements can make the game more engaging and customizable Live DemoSource code Conclusionbuilding front end projects is an excellent way to enhance your coding skills and embark on a journey from zero to hero in the world of web development Regardless of your technical background beginner projects provide an opportunity to grasp essential concepts while enjoying the learning process We explored various beginner friendly projects such as a password generator analog clock tic tac toe game and a simple website These projects not only allow you to practice your coding skills but also serve as tangible proof of your progress as you create functional and visually appealing applications Remember the path to becoming a skilled front end developer requires practice and hands on experience The more you immerse yourself in building projects the closer you get to achieving your goal Don t be afraid to experiment make mistakes and learn from them Every project you undertake adds to your knowledge and expertise With the right prerequisites in place such as HTML CSS and JavaScript skills you have a solid foundation to embark on these projects By following the guidelines planning your approach and staying dedicated you can build impressive projects that showcase your abilities So what are you waiting for Start your coding journey today with these beginner projects and let your creativity flourish With each project you ll gain confidence problem solving skills and a deeper understanding of front end development Remember the path from zero to hero is about the dedication passion and willingness to learn Embrace the power of building projects and before you know it you ll transform into a front end development hero Happy coding My name is Hussaini Ahmed I am a front end developer I also write about front end languages frameworks and latest technologies I d loved to hear your thought on this article Feel free to drop a comment below or reach out to me via UpworkGithubWhatsAppTwitterLinkedIn 2023-05-30 16:10:36
海外TECH DEV Community Como ter um console de jogos mudou minha vida [PT-BR] https://dev.to/andredarcie/como-ter-um-console-de-jogos-mudou-minha-vida-pt-br-3ehl Como ter um console de jogos mudou minha vida PT BR Antes de tudo éimportante ressaltar que embora seja incrível ter o hobby de jogar videogame isso pode levar a um estilo de vida sedentário Portanto éimportante praticar atividades físicas diárias ter uma boa qualidade de sono e evitar o vício em jogos limitando o tempo de jogo a duas horas por dia Dito isso vamos discutir um dos hobbies mais divertidos de todos os tempos e como aprimorá lo Evitando ficar o dia todo no mesmo ambienteComo um desenvolvedor de software sou parte do público alvo deste site Nos dias de hoje écomum trabalhar em casa e muitas pessoas desejam continuar nesse modelo No entanto passar quase o dia inteiro no mesmo lugar pode ser como estar preso sem ter cometido um crime Embora vocêpossa se acostumar isso pode ser prejudicial para a mente e o corpo Para melhorar minha qualidade de vida decidi adotar uma abordagem que nunca pensei que tomaria comprar uma TV e um console Agora meu ambiente de lazer onde jogo videogame écompletamente separado do ambiente do computador e do escritório Isso não sómelhorou significativamente minha qualidade de vida mas também me permitiu focar melhor em ambas as atividades Evitando distraçõesQuando eu jogava no PC não conseguia passar muito tempo sem me distrair Ficava pressionando Alt Tab e começava a ler redes sociais notícias e navegar pela internet por horas sem perceber Tudo o que eu queria era jogar um pouco distrair a mente e descansar mentalmente mas de alguma forma eu sempre era puxado para fora do jogo para fazer outras coisas no PC O Nintendo Switch não possui acesso a redes sociais nem àinternet livremente e isso éuma feature não um problema Isso me ajuda a focar completamente no que estou fazendo que no caso éjogar Experiência de usuárioEmbora eu trabalhe na área de Tecnologia da Informação às vezes écansativo ter que configurar os jogos para rodarem corretamente no meu computador Nem todos os jogos são otimizados para todos os tipos de computadores possíveis então sempre tenho que fazer ajustes finos testar a taxa de quadros por segundo FPS desativar recursos alterar a resolução e atépensar em adquirir peças melhores ou fazer um upgrade de memória Com o console ésóligá lo colocar o jogo e começar a jogar sem preocupações dores de cabeça ou configurações complicadas Atualmente possuo o PlayStation e não me preocupo em gastar com novas peças para ele A única coisa éque daqui a seis anos serálançado o PlayStation mas atéláminha mente estarátranquila Lazer de qualidadeAtualmente cada vez mais pessoas estão viciadas em seus celulares passando horas distraídas vendo vídeos Eu no final do dia antes de dormir depois de passar horas navegando a internet no celular me pego pensando nada disso valeu a pena Se eu tivesse me dedicado apenas a jogar algum jogo teria experimentado algo muito mais divertido e interessante verdadeiramente distraído minha mente e recarregado minhas energias ConclusãoEmbora possa parecer um detalhe ter um console fez uma diferença drástica na minha vida levando em consideração que meu hobby principal éjogar e que trabalho em casa Essa mudança proporcionou uma melhoria significativa no meu bem estar e na qualidade do meu tempo de lazer 2023-05-30 16:10:25
Apple AppleInsider - Frontpage News Apple tells developers to 'Code new worlds' in WWDC email https://appleinsider.com/articles/23/05/30/apple-tells-developers-to-code-new-worlds-in-wwdc-email?utm_medium=rss Apple tells developers to x Code new worlds x in WWDC emailApple has sent an email to developers giving them a one week warning that WWDC is happening as well as a not so subtle nudge about its long rumored MR headset In an email sent to developers on Tuesday titled One week until WWDC Apple offers yet another reminder that a major event in the Apple developer calendar is happening soon Just like it did for the Apple Event page earlier on Tuesday the email largely informs the reader about WWDC s dates that the keynote is happening on June and offering a link to add the event to their calendar Read more 2023-05-30 16:54:15
Apple AppleInsider - Frontpage News App Store's 'xrOS' awareness is the latest hint of WWDC headset launch https://appleinsider.com/articles/23/05/30/app-stores-xros-awareness-is-the-latest-hint-of-wwdc-headset-launch?utm_medium=rss App Store x s x xrOS x awareness is the latest hint of WWDC headset launchApple has started to lay the groundwork for the development of apps for its rumored mixed reality headset with the App Store knowing that apps could be made for xrOS A render of a potential Apple headset AppleInsider Apple s WWDC presentation on June is widely expected to include the launch of the company s first foray into the AR and VR market Accompanying that should be resources for developers to produce apps for the headset with Apple needing to put in place systems for their development Read more 2023-05-30 16:07:37
Apple AppleInsider - Frontpage News Data about Apple's AR headset screens has been leaked https://appleinsider.com/articles/23/05/30/data-about-apples-ar-headset-screens-has-been-leaked?utm_medium=rss Data about Apple x s AR headset screens has been leakedDisplay analyst Ross Young claims to have specifications for the screens in Apple s forthcoming Apple AR headset believed to be announced at WWDC Mockup of a possible Apple headset designApple hasn t announced any details of its first foray into Augmented Reality headsets and won t until at least WWDC But any headset will feature two screens one for each of the wearer s eyes and Young says he has the details Read more 2023-05-30 16:25:23
Apple AppleInsider - Frontpage News iPhone 16 Pro will be biggest iPhone yet, aspect ratio rumored to change https://appleinsider.com/articles/23/05/30/iphone-16-pro-display-aspect-ratio-rumored-to-change?utm_medium=rss iPhone Pro will be biggest iPhone yet aspect ratio rumored to changeThe iPhone Pro will not only be larger but it will also sport a new aspect ratio making the smartphone taller than the iPhone Pro and earlier generations A render of an iPhone ProSpeculation about the iPhone Pro models largely covers the display of the device with claims that it will be bigger than the iPhone Pro and its predecessors While it will allegedly be bigger it may also seem to be slightly different in terms of aspect ratio Read more 2023-05-30 16:25:43
海外TECH Engadget Amazon ditches Alexa’s celebrity voices and issues no refunds https://www.engadget.com/amazon-ditches-alexas-celebrity-voices-and-issues-no-refunds-165511049.html?src=rss Amazon ditches Alexa s celebrity voices and issues no refundsIf you ve been saving up to integrate Shaq s voice into your Alexa devices you ve officially blown it Amazon is ditching all of its Alexa enabled celebrity voices including Shaquille O Neal Melissa McCarthy and say it ain t so Samuel L Jackson The distinct voice options will no longer be available for purchase and will no longer function even if you made a purchase a while back as reported by The Verge That brings us to the topic of refunds and it looks like there won t be any This isn t earth shattering news as the voice options launched for just before moving up to in recent months Still buying something and having it vaporize into nothing is never fun for consumers We ve reached out to Amazon for clarification on these refunds and will update when we hear back Samuel L Jackson has already flown the coop with an official announcement on the purchase page about his voice avatar s early retirement Melissa McCarthy and Shaq still work but only until September To the uninitiated this feature was an add on for Alexa that transformed its usual chirpy tones into that of a celebrity This was all fairly limited when compared to Alexa s full feature set as the celebs won t do reminders and don t integrate with many skills They do however tell jokes answer questions and complete simple voice assisted tasks The service started with Jackson in but extended to include Shaq and McCarthy shortly thereafter So why did Amazon shut the feature down Alexa s no longer the hottest thing in the universe and the company s hardware division recently laid off thousands of people involved with designing and manufacturing Echo speakers so that could be part of it Again the feature set with these voices was on the anemic side so maybe not enough people bought them to offset the licensing costs Finally there s the AI elephant in the room Reports indicate that Amazon is building its own large language model LLM like ChatGPT to radically transform Alexa and celebrity voices may no longer fit into that vision This article originally appeared on Engadget at 2023-05-30 16:55:11
海外TECH Engadget 'Ratchet and Clank: Rift Apart' is coming to PC on July 26th https://www.engadget.com/ratchet-and-clank-rift-apart-is-coming-to-pc-on-july-26th-162146036.html?src=rss x Ratchet and Clank Rift Apart x is coming to PC on July thFresh on the heels of an in depth look at Marvel s Spider Man gameplay there s more news from the Insomniac Games camp The studio s previous title s Ratchet and Clank Rift Apart is coming to PC on July th As is often the case with PC versions of PlayStation exclusives there are some extra bells and whistles here There are new quot ray traced shadows for natural light in outdoor areas quot which allow for quot realistic shadows with natural gradients in softness quot as Julian Huijbregts an online community specialist at Nixxes the Sony studio that s working on the port notes on the PlayStation Blog The gameplay and cutscenes have been optimized for ultra wide displays including aspect ratios of and even for triple monitor setups Along with unlocked framerates there s support for upscaling tech including NVIDIA DLSS AMD FSR Intel XeSS and Insomniac s own Temporal Injection as well as NVIDIA Reflex and NVIDIA DLAA anti aliasing You can opt to use a keyboard and mouse with fully customizable controls or a controller Plug in a DualSense and you ll be able to experience the same haptic feedback and dynamic trigger effects that you would on PS I finally got around to playing Ratchet and Clank Rift Apart after it hit PlayStation Plus recently and enjoyed it immensely It s a breathtakingly gorgeous game with strong combat captivating characters and a smart script Insomniac also makes better use of the DualSense s capabilities than most studios Fingers crossed that Insomniac and Nixxes can avoid the kinds of technical issues that have plagued PC versions of other Sony games The Last of Us Part nbsp Iron Galaxy worked with Naughty Dog on that port and Horizon Zero Dawn which Nixxes helped to fix both had notable problems at the outset on PC Ratchet and Clank Rift Apart relies on the speedy load times of the PlayStation to make the dimension hopping feature work seamlessly With that and the stellar visuals in mind it s likely that you ll need a beefy gaming rig to get the most out of the port So it s probably worth waiting for Sony to reveal the PC specs before locking in a pre order on Steam or the Epic Games Store This article originally appeared on Engadget at 2023-05-30 16:21:46
金融 金融庁ホームページ 「デジタル・分散型金融への対応のあり方等に関する研究会」(第11回)を開催します。 https://www.fsa.go.jp/news/r4/singi/20230530.html Detail Nothing 2023-05-30 17:00:00
ニュース BBC News - Home Artificial intelligence could lead to extinction, experts warn https://www.bbc.co.uk/news/uk-65746524?at_medium=RSS&at_campaign=KARANGA nuclear 2023-05-30 16:32:02
ニュース BBC News - Home TV fraud gang jailed for illegally streaming Premier League games https://www.bbc.co.uk/news/uk-65697595?at_medium=RSS&at_campaign=KARANGA cheap 2023-05-30 16:28:58
ニュース BBC News - Home Royal Blood: How not to win over a festival crowd https://www.bbc.co.uk/news/newsbeat-65756149?at_medium=RSS&at_campaign=KARANGA weekend 2023-05-30 16:46:01
ニュース BBC News - Home French Open 2023 results: Daniil Medvedev beaten in first round by Thiago Seyboth Wild https://www.bbc.co.uk/sport/tennis/65755951?at_medium=RSS&at_campaign=KARANGA round 2023-05-30 16:19:56
ニュース BBC News - Home France prop Haouas given jail sentence for hitting wife https://www.bbc.co.uk/sport/rugby-union/65758424?at_medium=RSS&at_campaign=KARANGA abuse 2023-05-30 16:51:16
Azure Azure の更新情報 Public Preview: Azure Data Explorer bindings for Azure Functions https://azure.microsoft.com/ja-jp/updates/public-preview-azure-data-explorer-bindings-for-azure-functions/ preview 2023-05-30 17:00:06

コメント

このブログの人気の投稿

投稿時間: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件)