search
HomeTechnology peripheralsIt IndustryBuild a Preact App with Authentication

Build a Preact App with Authentication

This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.

React is a fast, and lightweight library, which has led to fast adoption across the SPA (single-page app) ecosystem. Preact is an even lighter-and-faster alternative to React, weighing in at a measly 3kb! For less complex applications, it can be a great choice.

In this tutorial, you’ll build a basic Preact application with a couple of pages and user authentication using the Okta Sign-In Widget.

Key Takeaways

  • Utilize PreactCLI to efficiently scaffold a new Preact application, leveraging its compatibility with some React plugins while enjoying a lighter, faster framework.
  • Integrate user authentication in your Preact app using the Okta Sign-In Widget, simplifying the process of managing user sessions and security.
  • Implement Higher-Order Components (HOCs) for authentication to manage user login states and protect routes within your Preact application effectively.
  • Employ Preact’s router and custom Redirect components to handle navigation and route protection, ensuring users are directed appropriately based on their authentication status.
  • Update various components, such as the Login and Profile pages, to interact with the authentication logic, providing a seamless user experience and personalization based on user data.

Bootstrap Your App With PreactCLI

To get your project started, you’ll install the PreactCLI using NPM.

npm install -g preact-cli

Once you have the CLI installed, run the command to create a base Preact application:

preact create okta-preact-example

This command will chug along for a few minutes scaffolding a basic Preact app and installing all the dependencies. Once it’s done, you should see a bunch of information on the command line informing you of what you can do next.

Change into the application directory.

cd okta-preact-example

Then start the application, just to make sure everything worked as expected.

npm start

You should see a quick build run and the screen will clear and show you that the application is running at http://localhost:8080. When you open up that URL in your browser, you should see a page like this:

Build a Preact App with Authentication

Some Things To Note About PreactCLI

Even though the PreactCLI-generated app looks a lot like a React app generated by create-react-app, and you can even use some of the React plugins (like React-Router) in your Preact application, there are some significant differences.

For instance, unlike the ReactCLI, there is no way to eject the Webpack configuration. Instead Preact encourages developers to customize Webpack by creating a file called preact.config.js, using Preact’s Webpack Config Helpers and exporting functions to change the way Webpack behaves.

Even though the PreactCLI says the application is running at http://0.0.0.0:8080, use http://localhost:8080. It’s the same thing and when you set up your application in the Okta dashboard, you’ll set http://localhost:8080 as your base URL and callback URL, so this just makes sure that you can call the Okta APIs.

Create Your Okta Application

Now that you have the basic shell of an application, it’s time to add user authentication. If you don’t already have one, create a free (forever) account at Okta.

Once you’ve created an account, go to the admin dashboard and click on “Applications” in the page menu. Then click the green “Add Application” button, then the green “Create New App” button, so that you see a modal window like:

Build a Preact App with Authentication

Choose “SPA” from the Platform buttons. Click the “Next” button to create your application.

This will take you to a screen to “Application Settings” page of the Create Application wizard. Enter “OktaPreactExample” in the Application name field and add http://localhost:8080 as your base URI and as a login redirect URI. When you’re done, your form should look like this:

Build a Preact App with Authentication

You’ll need to create a user (if you don’t already have one) and assign your new application to them as well. Or you can log in with the credentials you use to log in to your Okta account (the admin user).

Install the Okta Sign In Widget

The easiest way to get Okta’s authentication into your new Preact application will be to use Okta’s Sign-In Widget. You’ll install it with npm using:

npm install -g preact-cli

You’ll also need to install preact-router with:

preact create okta-preact-example

Add an Auth Higher-Order Component

With that done, you now need to add some Higher-Order Components to help with authentication.

Add a file called auth.js in the /src/lib folder and add the following code:

cd okta-preact-example

In the first line of code, you can tell something’s different. The h module in Preact is what turns JSX into DOM elements. Normally, React would use the React library to generate React.createElement statements to make DOM elements from JSX. Preact uses the h library to make something like h('div', {class:'something'}, 'Content') statements to do that.

Next, you imported route from preact-router right below the h import. This is what is used by Preact to do the redirects in the login function. Notice that the Auth class is just a regular function and does not extend Component. In the constructor, the internal functions were bound with the this context from the Auth class.

Then enter your Okta organization URL and client ID to the Okta Sign-In Widget configuration. Your Organization URL will be the URL you use when you log into your Okta account (e.g. http://dev-12345.oktapreview.com) and you can get your client ID from the application’s property page in the administrative dashboard on the “General” tab for your application (obviously, yours won’t be blurred out):

Build a Preact App with Authentication

You’ll also want to change the redirectUri property to http://localhost:8080 because the Preact uses port 8080 instead of 3000 for normal React apps.

The login function simply routes the user to the login page, while the logout function clears the tokens saved in the widget’s token manager, calls signOut on the widget, and redirects the user to the root of the application.

Finally, a singleton of the Auth class is created to be shared by all the components, and is passed in as a prop called auth to any component that you wrap in withAuth.

Create a Widget Wrapper

Create a file in your /src/lib folder called OktaSignInWidget.js. Enter the code for this component:

npm install -g preact-cli

Here, the componentDidMount method renders the Okta Sign-In Widget to the div in your render method and the componentWillUnmount function removes the widget.

In the render method, there’s some strange-looking code. This allows you to set a reference to the current element into a variable called widgetContainer and then use it in the componentDidMount as this.widgetContainer. Neat, huh? Thanks to Matt Raible for showing me that trick!

Create a Redirect Component

The React-Router has a Redirect component in it, but the Preact router doesn’t, so you’ll need one. Luckily, it’s easy to create your own. In your /src/lib folder create a file called Redirect.js and add the following code:

preact create okta-preact-example

This is just a component that will redirect based on a URL passed to it. In this case, the use will be redirected using the window.location mechanism, mostly because you’ll want to refresh the page. You could also just use route(this.props.to.pathname) and let Preact’s router redirect the user.

Create a Login Component

Next, create a Login folder in src/routes. In that folder create an index.js file and a style.css file. This just follows along with the way the Preact CLI creates components.

In the index.js file, create a Login component, wrapped in the withAuth component. First, by importing the modules needed:

npm install -g preact-cli

Start the component by wrapping in the withAuth higher-order component you created earlier, and set the beginning state. Here, you’ll have the redirectToReferrer set to false by default.

preact create okta-preact-example

In the componentWillMount lifecycle function, wire up the onSuccess and onError functions and create them in your component.

cd okta-preact-example

You’ll notice your component passes handling of the authentication back to the higher-order component. This is a prime example of the benefits of higher-order components and composition in JavaScript.

Finally, create the render function that will make the decision about showing the login widget or, if the user is already logged in, redirecting them to the home page. You could also redirect the user to the page they were going to when they were redirected to the login page, but let’s skip that for now.

npm start

You’ll notice here that Preact is a little different in that it gives you handles to props and state as parameters to the render function. This code simply uses destructuring of those parameters to make using location, auth and redirectToReferrer simple without having a ton of this.props.{whatever}.

So your final /src/routes/login/index.js file will look like:

npm install @okta/okta-signin-widget --save

Update the Profile Page

Now that you have the Login component and it is using the Okta Sign-In Widget, use the auth component you created and update the profile page (in /src/routes/profile/index.js) to give you some more information about the user. This is what your final /src/routes/profile/index.js file should look like:

npm install preact-router --save

You’ve added the authentication protection at the Component level in the componentWillMount function of the component. If the user is authenticated, it calls the getCurrentUser function on the higher-order component and adds the user to the component’s state. In the render function, you simply output the user’s name and email.

Update the Header Component

Now you just need to get the routes into your application and get the menu to link to them. Start by changing the /src/components/header/index.js file to:

import {h} from 'preact';
import { route } from 'preact-router';
import OktaSignIn from '@okta/okta-signin-widget/dist/js/okta-sign-in.min.js';
import '@okta/okta-signin-widget/dist/css/okta-sign-in.min.css';
import '@okta/okta-signin-widget/dist/css/okta-theme.css';

class Auth {
  constructor() {
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);

    this.widget = new OktaSignIn({
      baseUrl: 'https://{yourOktaDomain}.com/',
      clientId: '{clientId}',
      redirectUri: 'http://localhost:8080',
      authParams: {
        responseType: ['id_token', 'token'],
        scopes: ['openid', 'email', 'profile']
      }
    });
  }

  isAuthenticated() {
    // Checks if there is a current accessToken in the TokenManger.
    return !!this.widget.tokenManager.get('accessToken');
  }

  getCurrentUser(){
    return this.widget.tokenManager.get('idToken');
  }

  login() {
    // Redirect to the login page
    route('/login/');
  }

  async logout() {
    this.widget.tokenManager.clear();
    await this.widget.signOut();
    location = '/';
  }

  handleAuthentication(tokens) {
    for (let token of tokens) {
      if (token.idToken) {
        this.widget.tokenManager.add('idToken', token);
      } else if (token.accessToken) {
        this.widget.tokenManager.add('accessToken', token);
      }
    }
  }
}

// create a singleton
const auth = new Auth();
export const withAuth = WrappedComponent => props =>
  <wrappedcomponent auth="{auth}"></wrappedcomponent>;

This will show the “Login” button if the user is not logged in and the “Logout” button if they are. It will also only show the “Profile” menu item to those users who are logged in.

Change Your Routing

Finally, change the routes in your /src/components/app.js file so that your application knows about your new routes and how to handle them. So your new app.js file will look like:

import { h, Component } from 'preact';

export default class OktaSignInWidget extends Component {
  componentDidMount() {
    this.widget = this.props.widget;
    this.widget.renderEl({ el: this.widgetContainer }, this.props.onSuccess, this.props.onError);
  }

  componentWillUnmount() {
    this.widget.remove();
  }

  render() {
    return <div ref="{(div)"> { this.widgetContainer = div; }} />
  }
};

<p>All that really changed is that you imported the newly created Login component and remove the user property being passed into the Profile component and added a new route for the Login component.</p>
<h2 id="Run-Your-New-Preact-Application">Run Your New Preact Application!</h2>
<p>You should now be able to save your work and run npm start in the root folder and see a fully-functioning Preact application with user authentication via Okta!</p>
<p>There are a lot of similarities between Preact and React, but there are some key differences. Preact is meant for applications where keeping the size of the download small is critical. There are some nice conveniences in the Preact router, but there are some things missing (like withRouter). There are also some neat conveniences, like having props and state passed to the render function. All in all, I think Preact is neat, but I could see really needing a full-fledged React for complex apps.</p>
<h2 id="Learn-More">Learn More</h2>
<p>You can find out more about Preact from their website and Preact-Router from the Github repository.</p>
<p>You can also get the complete code for this article from the Okta Developer Github repository.</p>
<p>As always, if you have any questions, comments or concerns about the article, the code, Preact or Okta, feel free to reach out to me via email, or hit me up in the comments or via Twitter @leebrandt.</p>



<h2 id="Frequently-Asked-Questions-about-Building-a-Preact-App-with-Authentication">Frequently Asked Questions about Building a Preact App with Authentication</h2>



<h3 id="What-is-Preact-and-how-does-it-differ-from-React">What is Preact and how does it differ from React?</h3> <p>Preact is a fast, lightweight JavaScript library that is similar to React. It is designed to be small and efficient, with a compressed size of just 3KB. Preact provides the same modern UI library and features of React, such as Virtual DOM diffing and Components, but with a smaller footprint. It’s perfect for mobile devices where bandwidth and performance can be issues. Preact also aims to be as close to React as possible in API, making it easy for React developers to start using Preact with minimal adjustments.</p>  <h3 id="How-do-I-set-up-a-Preact-project">How do I set up a Preact project?</h3> <p>Setting up a Preact project is straightforward. You can use preact-cli, a command-line tool that helps you create and manage Preact projects. To install it, you need to have Node.js and npm installed on your computer. Once installed, you can create a new project by running the command preact create default my-project, where ‘my-project’ is the name of your project. This will create a new directory with the project files and dependencies.</p>  <h3 id="How-do-I-add-authentication-to-my-Preact-app">How do I add authentication to my Preact app?</h3> <p>Adding authentication to your Preact app involves several steps. First, you need to install and import the necessary libraries, such as preact-router for routing and preact-cookies for handling cookies. Then, you need to create a login form and an authentication service that will handle the login requests and manage the user’s session. Finally, you need to protect your routes by checking if the user is authenticated before rendering the protected components.</p>
<h3 id="How-do-I-handle-routing-in-Preact">How do I handle routing in Preact?</h3> <p>Preact uses preact-router for routing. It’s a simple and small router that uses the browser’s history API. To use it, you need to install it via npm and import it into your project. Then, you can define your routes using the <router> component and <route> components. Each <route> component represents a page and has a ‘path’ prop that matches the URL.</route></route></router></p>  <h3 id="How-do-I-manage-state-in-Preact">How do I manage state in Preact?</h3> <p>Preact uses a concept called “props” and “state” to manage data. Props are passed to components from their parent, while state is managed within components. Preact’s state management is similar to React’s. You can use the this.setState() method to update the state and re-render the component. For complex state management, you can use libraries like Redux or MobX.</p>  <h3 id="How-do-I-use-hooks-in-Preact">How do I use hooks in Preact?</h3> <p>Preact supports hooks, a feature that allows you to use state and other React features without writing a class. To use hooks in Preact, you need to import them from ‘preact/hooks’. The hooks API in Preact is the same as in React, so you can use hooks like useState, useEffect, and useContext in the same way.</p>  <h3 id="How-do-I-test-my-Preact-app">How do I test my Preact app?</h3> <p>You can test your Preact app using testing libraries and frameworks like Jest and Enzyme. Jest is a JavaScript testing framework that works well with Preact, while Enzyme is a testing utility for React that can also be used with Preact. You can also use preact-test-utils, a library that provides helper functions for testing Preact components.</p>  <h3 id="How-do-I-deploy-my-Preact-app">How do I deploy my Preact app?</h3> <p>You can deploy your Preact app to various hosting platforms like Netlify, Vercel, and GitHub Pages. To deploy, you need to build your app for production by running the npm run build command. This will create a ‘build’ directory with your compiled app. Then, you can deploy this directory to your chosen hosting platform.</p>  <h3 id="How-do-I-optimize-my-Preact-app-for-performance">How do I optimize my Preact app for performance?</h3> <p>Preact is already optimized for performance out of the box, but there are several things you can do to make your app even faster. This includes code-splitting, lazy-loading components, and optimizing images and other assets. You can also use Preact’s shouldComponentUpdate() lifecycle method to prevent unnecessary re-renders.</p>  <h3 id="Can-I-use-React-libraries-and-components-in-my-Preact-app">Can I use React libraries and components in my Preact app?</h3> <p>Yes, you can use most React libraries and components in your Preact app thanks to ‘preact-compat’, a thin layer over Preact that attempts to achieve 100% compatibility with React. This means you can switch to Preact from React with minimal changes to your code. However, due to the small size of Preact, some features of React are not supported out of the box.</p>
</div>

The above is the detailed content of Build a Preact App with Authentication. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Building a Network Vulnerability Scanner with GoBuilding a Network Vulnerability Scanner with GoApr 01, 2025 am 08:27 AM

This Go-based network vulnerability scanner efficiently identifies potential security weaknesses. It leverages Go's concurrency features for speed and includes service detection and vulnerability matching. Let's explore its capabilities and ethical

Top 10 Best Free Backlink Checker Tools in 2025Top 10 Best Free Backlink Checker Tools in 2025Mar 21, 2025 am 08:28 AM

Website construction is just the first step: the importance of SEO and backlinks Building a website is just the first step to converting it into a valuable marketing asset. You need to do SEO optimization to improve the visibility of your website in search engines and attract potential customers. Backlinks are the key to improving your website rankings, and it shows Google and other search engines the authority and credibility of your website. Not all backlinks are beneficial: Identify and avoid harmful links Not all backlinks are beneficial. Harmful links can harm your ranking. Excellent free backlink checking tool monitors the source of links to your website and reminds you of harmful links. In addition, you can also analyze your competitors’ link strategies and learn from them. Free backlink checking tool: Your SEO intelligence officer

Another national product from Baidu is connected to DeepSeek. Is it open or follow the trend?Another national product from Baidu is connected to DeepSeek. Is it open or follow the trend?Mar 12, 2025 pm 01:48 PM

DeepSeek-R1 empowers Baidu Library and Netdisk: The perfect integration of deep thinking and action has quickly integrated into many platforms in just one month. With its bold strategic layout, Baidu integrates DeepSeek as a third-party model partner and integrates it into its ecosystem, which marks a major progress in its "big model search" ecological strategy. Baidu Search and Wenxin Intelligent Intelligent Platform are the first to connect to the deep search functions of DeepSeek and Wenxin big models, providing users with a free AI search experience. At the same time, the classic slogan of "You will know when you go to Baidu", and the new version of Baidu APP also integrates the capabilities of Wenxin's big model and DeepSeek, launching "AI search" and "wide network information refinement"

Behind the first Android access to DeepSeek: Seeing the power of womenBehind the first Android access to DeepSeek: Seeing the power of womenMar 12, 2025 pm 12:27 PM

The rise of Chinese women's tech power in the field of AI: The story behind Honor's collaboration with DeepSeek women's contribution to the field of technology is becoming increasingly significant. Data from the Ministry of Science and Technology of China shows that the number of female science and technology workers is huge and shows unique social value sensitivity in the development of AI algorithms. This article will focus on Honor mobile phones and explore the strength of the female team behind it being the first to connect to the DeepSeek big model, showing how they can promote technological progress and reshape the value coordinate system of technological development. On February 8, 2024, Honor officially launched the DeepSeek-R1 full-blood version big model, becoming the first manufacturer in the Android camp to connect to DeepSeek, arousing enthusiastic response from users. Behind this success, female team members are making product decisions, technical breakthroughs and users

DeepSeek's 'amazing' profit: the theoretical profit margin is as high as 545%!DeepSeek's 'amazing' profit: the theoretical profit margin is as high as 545%!Mar 12, 2025 pm 12:21 PM

DeepSeek released a technical article on Zhihu, introducing its DeepSeek-V3/R1 inference system in detail, and disclosed key financial data for the first time, which attracted industry attention. The article shows that the system's daily cost profit margin is as high as 545%, setting a new high in global AI big model profit. DeepSeek's low-cost strategy gives it an advantage in market competition. The cost of its model training is only 1%-5% of similar products, and the cost of V3 model training is only US$5.576 million, far lower than that of its competitors. Meanwhile, R1's API pricing is only 1/7 to 1/2 of OpenAIo3-mini. These data prove the commercial feasibility of the DeepSeek technology route and also establish the efficient profitability of AI models.

Midea launches its first DeepSeek air conditioner: AI voice interaction can achieve 400,000 commands!Midea launches its first DeepSeek air conditioner: AI voice interaction can achieve 400,000 commands!Mar 12, 2025 pm 12:18 PM

Midea will soon release its first air conditioner equipped with a DeepSeek big model - Midea fresh and clean air machine T6. The press conference is scheduled to be held at 1:30 pm on March 1. This air conditioner is equipped with an advanced air intelligent driving system, which can intelligently adjust parameters such as temperature, humidity and wind speed according to the environment. More importantly, it integrates the DeepSeek big model and supports more than 400,000 AI voice commands. Midea's move has caused heated discussions in the industry, and is particularly concerned about the significance of combining white goods and large models. Unlike the simple temperature settings of traditional air conditioners, Midea fresh and clean air machine T6 can understand more complex and vague instructions and intelligently adjust humidity according to the home environment, significantly improving the user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.