Skip to content

How To Authenticate Your SolidJS Routes With Solid Router

This article was written over 18 months ago and may contain information that is out of date. Some content may be relevant but please refer to the relevant official documentation or available resources for the latest information.

In this post, we will talk about how we can authenticate our SolidJS route with Solid Router. By the end of this article, we will understand what authentication is, and how it is used to guard routes in SolidJS using the Solid Router.

Overview

Route authentication has been around for a while, and is now a fundamental part of many applications like Facebook, Gmail, and Instagram. At this point, it’s about as ubiquitous as entering a password into a phone. Authentication through route guards in SolidJS can be achieved in two different ways. The first that we are going to cover in this app is the use of a Solid Router. The second is provided by Solid Start, which is more like a folder-based routing. It is a meta-framework (a framework built on another framework). At its core, it's powered by SolidJS and Solid Router. This article assumes that you have already set up a SolidJS project, and will not walk through that part of the process. If you have not yet spun up a project, you can find tutorials and instructions at SolidJS.

What is Authentication?

Authentication is a process of verifying the identity of the user. It provides access control to check if the user is authenticated. Authentication enables organizations to keep their networks secure by permitting only authenticated users or processes to gain access to their protected resources which, in our case, is the route in the application.

To learn more about authentication, you can check out the following;

What is a route guard?

A route guard helps to prevent unauthenticated users from accessing certain routes/parts in an application. For example, an app lock on a mobile phone can be seen as a guard. You may be able to access the phone and some apps, but you can’t access other apps.

We can also use parental controls on the phone, internet, and so on as a type of guard. You can read more about route guard.

Get Started

If you haven't installed the Solid Router in your project, run the command below:


  # Using NPM
  npm i @SolidJS/router

  # Using PNPM
  pnpm i @SolidJS/router

  # Using yarn
  yarn add @SolidJS/router

Solid Router is a universal router for SolidJS which works whether you're rendering on the client or the server. It was inspired by and combines the paradigms of React Router and the Ember Router. To read more, check out Solid Router

Having installed @SolidJS/router, we will be creating the following files;

  • Home: src/pages/Home.jsx
  • Signin: src/pages/Signin.jsx
  • Pricing: src/pages/Pricing.jsx
  • RouteGuard: src/RouteGuard/index.jsx
  • Header: src/components/Header/index.jsx
  • Header styles: src/components/Header/Header.module.css

Terminologies

  • useNavigate: a library provided to us by SolidJS Router that is used to navigate.
  • createEffect: creates a listener, which calls it's first argument when attached signals change.
  • Outlet: serves as the children associated with RouteGuard wrapper
  • NavLink: used to navigate between pages just like a tag which takes a property href for the page route path.

Home page

Below is the code we will paste in our home page file. But if you already have a content for this, you don't have to change it.

import appstyles from '../App.module.css';
export default function Home() {
  return (
    <div class={appstyles.wrapper}>
      <h2>Home page here</h2>
      <p>You can see this because you are authenticated</p>
    </div>
  );
}

This is just a simple page component with a style imported at the top.

Signin page

This is the content of our sign in page, but if have a content already, that's fine. The most important contents are the logIn function and the createEffect.

import { useNavigate } from "@SolidJS/router";
import { createEffect } from "solid-js";
import appstyles from "../App.module.css";

export default function SignIn () {
  const navigate = useNavigate();
  const logIn = () => {
    sessionStorage.setItem('token', 'mytokenisawesome');
    navigate('/home', { replace: true });
  };

  createEffect(() => {
    if(sessionStorage.getItem('token')) {
      navigate('/home', { replace: true })
    }
  })
  return (
    <div class={appstyles.wrapper}>
      <h2>Sign In Page</h2>
      <p>You can see this because you are not authenticated</p>
      <button class={appstyles.login_btn} onClick={logIn}>Log In</button>
    </div>
  )
}

The logIn function will be called when the login button is clicked. When clicked, a hardcoded token is saved in the session storage. The user is then navigated to the home page, which by default, can only be accessed if the user has been authenticated. The createEffect ensures the authenticated user won't access the sign in page.

Pricing page

This is just another page which, in this project, represents another protected page that could only be accessed by an authenticated user.


import appstyles from "../App.module.css";

export default function Pricing() {
  return (
    <div class={appstyles.wrapper}>
      <h2>Pricing page here</h2>
      <p>You can see this because you are authenticated</p>
      <i>Here you can find all prices</i>
    </div>
  );
}

This is just a simple page component with a style imported at the top.

RouteGuard Component


import { Outlet, useNavigate } from "@SolidJS/router";
import { createEffect } from "solid-js";
import Header from "../components/Header";

export default function RouteGuard () {
  const navigate = useNavigate();
  const token = sessionStorage.getItem('token');

  createEffect(() => {
    if(!token) {
      navigate('/signin', { replace: true });
    }
  })

  return (
    <div>
      <Header />
      <Outlet />
    </div>
  )
}

This serves as the wrapper for routes you want to protect from unauthenticated users. If there is no token in the session storage, the user will be routed to the signin page.

Header component

If you already have the content for the header file, you don't have to change it. All you need is the logOut function.


import { NavLink, useNavigate } from "@SolidJS/router";
import styles from './Header.module.css';

export default function Header() {
  const navigate = useNavigate();

  const logOut = () => {
    sessionStorage.removeItem('token');
    navigate('/signin', { replace: true });
  }
  return (
    <div class={styles.container}>
      <h3>My SolidJS App</h3>
      <div class={styles.links}>
        <NavLink href="/home">
          Home
        </NavLink>
        <NavLink href="/pricing">
          Pricing
        </NavLink>
      </div>
      <button class={styles.logout_btn} onClick={logOut}>Log out</button>
    </div>
  );
}

Above, we have styles imported from the header CSS module, and we have a logOut function that is used to remove the token from the session storage and also navigate the user to the signin page.

Header styles

This is the style for the header component.

.container {
  padding: 0.5rem 1rem;
  background-color: rgb(34, 80, 130);
  color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.links {
  color: #fff;
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: flex-end;
  gap: 1rem;
  font-size: 1rem;
  text-decoration: none;
  padding: 0 1.5rem;
  text-transform: uppercase;
}
.links a:link, a {
  color: #fff;
  text-decoration: none;
}

.logout_btn {
  padding: 0.5rem 0.86rem;
  background-color: #fff;
  color: rgba(255, 0, 0, 0.795);
  text-transform: uppercase;
  border: 0;
  outline: none;
  border-radius: 0.3rem;
  font-weight: 800;
  cursor: pointer;
  transition: background-color 0.2s ease-in-out;
}

.logout_btn:hover {
  background-color: rgb(239, 236, 236);
}

Updates for src/App.jsx

This file is where the route is managed, and where we grouped certain routes we wanna guard or protect from unauthenticated users.

import { Route, Routes } from '@SolidJS/router';
import Home from './pages/Home';
import SignIn from './pages/Signin';
import RouteGuard from './RouteGuard';
import Pricing from './pages/Pricing';

function App() {
  return (
    <Routes>
      <Route path="/signin" component={SignIn} />
      <Route path="/" component={RouteGuard}>
        <Route path="/home" component={Home} />
        <Route path="/pricing" component={Pricing} />
      </Route>
      <Route path="*" element={()=> <div>Page Not found!!!</div>} />
    </Routes>
  );
}

export default App;

Update for src/App.module.css


.login_btn {
  padding: 0.5rem 0.86rem;
  background-color: rgb(34, 80, 130);
  color: #fff;
  text-transform: uppercase;
  border: 0;
  outline: none;
  border-radius: 0.3rem;
  font-weight: 800;
  cursor: pointer;
  transition: background-color 0.2s ease-in-out;
}

.login_btn:hover {
  background-color: rgb(27, 64, 104);
}

.wrapper {
  padding: 1rem;
}

Updates for src/index.jsx

We have to update this file by wrapping our App with Router


/* @refresh reload */
import { render } from 'solid-js/web';
import { Router } from '@SolidJS/router';

import './index.css';
import App from './App';

render(() => (
  <Router>
    <App />
  </Router>
), document.getElementById('root'));

Update for src/index.css

a.active, a:active {
  text-decoration: underline !important;
  text-decoration-line: underline;
  text-decoration-style: wavy !important;
  text-decoration-color: rgba(255, 0, 0, 0.795) !important;
  text-underline-offset: 2px;
  text-decoration-thickness: from-font;
}

Conclusion

In this article, we were able to understand what authentication is, and how to create a route guard which is very important when trying to prevent certain users from accessing certain routes in our application. I hope we have been able to help you see the possibilities of making use of SolidJS and Solid Router to build a well-authenticated application. If you are having issues, you can check out the repo for SolidJS-route-guard. Don't forget that you can see, in detail, how this was maximized in one of This Dot's open source project starter.dev GitHub Showcases.

Happy coding!

This Dot is a consultancy dedicated to guiding companies through their modernization and digital transformation journeys. Specializing in replatforming, modernizing, and launching new initiatives, we stand out by taking true ownership of your engineering projects.

We love helping teams with projects that have missed their deadlines or helping keep your strategic digital initiatives on course. Check out our case studies and our clients that trust us with their engineering.

You might also like

Introducing the New SolidJS and Tailwind CSS Starter Kit cover image

Introducing the New SolidJS and Tailwind CSS Starter Kit

We are delighted to announce our SolidJS + Tailwind Starter Kit on Starter.dev to help you build your next project with SolidJS and Tailwind CSS in no time. In this article, we will walk you through the kit, and how it is a great option for building your next project. This kit has been designed to build tiny and optimized web applications on both the JavaScript and CSS sides. It's very useful when the load time of your application's files is critical, like when the internet connection is slow or when you are building a mobile application for a targeted audience. Why SolidJS? SolidJS is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you build web applications using a declarative API that you’re already familiar with. It’s a great alternative to React, Vue, and other popular JavaScript frameworks. It’s also a great choice for building static sites. The best feature of SolidJS is how tiny its build bundles are. It helps you ship less JavaScript to the browser. Why Tailwind CSS? Tailwind CSS is a utility-first CSS framework for rapidly building custom user interfaces. It makes it easy to build complex UIs without having to write custom CSS. And the best feature of Tailwind CSS is how customizable it is. It helps you ship a very small CSS file to the browser. --- Starter Kit Features - SolidJS - A declarative, efficient, and flexible JavaScript library for building user interfaces. - Tailwind CSS - A utility-first CSS framework for rapidly building custom user interfaces. - Vite - A build tool that aims to provide a faster and leaner development experience for modern web projects. - Storybook - An open-source tool for developing UI components in isolation for React, Vue, and Angular. - Vitest - A fast and simple test runner for Vite. - TypeScript - A typed superset of JavaScript that compiles to plain JavaScript. Tailwind CSS Tailwind CSS makes it easy to build complex UIs without having to write custom CSS. The best feature of Tailwind CSS is how customizable it is. It helps you ship a very small CSS file to the browser. Also, Tailwind CSS is great at scale, so you can add as many utilities as you want. Storybook Storybook is an open-source tool for developing UI components in isolation for React, Vue, Angular, and others. It makes building stunning UIs organized and efficient. It also helps you build components faster, and reuse them in your projects. It also helps you document your components. This kit comes with Storybook pre-configured. You can start using it right away. Why Vite? Vite is a build tool that aims to provide a faster and leaner development experience for modern web projects. It's a great alternative to Webpack. It's fast and easy to use. It also helps you ship less JavaScript to the browser. It's a great choice for building static sites. This kit comes with Vite pre-configured. You can start using it right away. Testing This kit comes with Vitest pre-configured. Vitest is a tool that is built with Vite in mind from the start, taking advantage of its improvements in DX, like its instant Hot Module Reload (HMR). This is Vitest, a blazing fast unit-test framework powered by Vite. It's a great alternative to Jest. It's fast and easy to use. How to get started? - Run npx @this-dot/create-starter to start a new project from one of the kits in the Starter CLI library. - Select the SolidJS, Tailwind kit from the CLI library options - Name your project - cd into your project directory and install dependencies using the tool of your choice (npm, yarn or pnpm) - Copy the contents of the .env.example file into a .env file When to use this kit? This kit is a great alternative to React and SCSS. It focuses on performance and developer experience by providing a fast and leaner development experience for modern web projects. It also helps you write less CSS, and less JavaScript. Options to scale the kit to fit your needs In this section, we will walk you through the options you have to scale the kit even further to fit your needs. We didn't want to add too many options to the kit in order to keep it simple and easy to use, but we also wanted to provide you with the ability to scale the kit. PWA PWA is a great way to make your app available offline, and installable on mobile devices. It caches your app's assets to make it load faster. It also helps you build a great user experience, and increase your app's engagement by providing push notifications. If you want to add PWA support to the kit, you can use the PWA Vite Plugin to add PWA support to the kit. It covers the PWA integrations for Vite, and the ecosystem with zero-configuration and is framework-agnostic. Conclusion So as we discussed in this article this SolidJS starter kit is a great way to start your new SolidJS project because it has most of the tools you need installed and preconfigured for you from Storybook to Testing, and even the PWA configurations. We hope you enjoyed this article, and we hope you will enjoy using the kit. If you have any questions or suggestions, please feel free to reach out to us on Twitter or Contact form....

Understanding Effects In SolidJS cover image

Understanding Effects In SolidJS

Understanding Effects In SolidJS In SolidJS, effects are a fundamental concept that helps developers manage side effects and reactive dependencies within their applications. Unlike standard functions that execute once and are done, effects in SolidJS are designed to automatically re-run whenever their dependencies change. This article will explore what effects are, how to use them, manage dependencies, handle multiple signals, and the lifecycle functions that enhance their functionality. What Are Effects? Effects in SolidJS are functions that automatically execute when the signals or reactive values they depend on change. This capability makes effects essential for managing side effects like DOM manipulations, data fetching, and subscriptions. Creating an Effect To create an effect in SolidJS, you use the createEffect function. This function takes a callback that runs whenever the effect is triggered by a change in its dependencies. ` In this example, the effect logs the user’s online status to the console. Each time the isOnline signal changes, the effect re-runs and logs the updated status. Managing Dependencies Dependencies in effects are the reactive values or signals that an effect observes. When any of these dependencies change, the effect re-runs. Interestingly, SolidJS automatically tracks these dependencies, meaning you don’t need to manually specify them, which reduces the risk of errors. When an effect is initialized, it runs once even if its dependencies haven't changed. This initial run is useful for setting up the effect, initializing variables, or subscribing to signals. ` Subscribing to Signals When an effect observes a signal, it essentially subscribes to it. This subscription allows the effect to re-run whenever the signal's value changes. ` In this example, the effect logs the current temperature whenever it changes. Managing Multiple Signals Effects in SolidJS can observe multiple signals simultaneously. This means that a single effect can track changes in multiple reactive values, re-running whenever any of them change. ` Here, the effect monitors both temperature and humidity signals. It re-runs when either signal changes, ensuring that it always logs the latest values. Nested Effects SolidJS allows effects to be nested within each other. Each nested effect independently tracks its own dependencies, ensuring that changes in an inner effect don’t inadvertently trigger an outer effect. ` In this example, changes to dependencies in the inner effect will not affect the outer effect. This separation prevents unintended behaviors and keeps effects isolated from one another. Lifecycle Functions SolidJS offers lifecycle functions that give you more control over when effects are initialized and disposed of. This can include running a side effect only once, or cleaning up a task when it is no longer needed. onMount The onMount function is used when you need to run a side effect only once, typically when a component is initialized. Unlike effects, which can re-run multiple times, onMount ensures that the callback is executed only once. ` This function is perfect for tasks like fetching data or setting up subscriptions that only need to happen once when the component mounts. onCleanup The onCleanup function is used to clean up tasks when a component is unmounted. This is particularly useful for clearing intervals, removing event listeners, or unsubscribing from services, thereby preventing memory leaks. ` In this example, onCleanup ensures that the interval is cleared when the component is unmounted, preventing it from running indefinitely in the background. Understanding the Execution Model of Effects in SolidJS SolidJS introduces a fine-grained reactivity) system that sets it apart in the UI development landscape. Unlike React, where effects are tied to component lifecycles and can sometimes trigger unnecessary re-renders, SolidJS operates at a much more granular level. It tracks dependencies down to individual signals or computations, enabling highly efficient updates. When you create an effect using createEffect, SolidJS automatically monitors every reactive signal accessed within that effect. It builds a precise dependency graph, which maps out exactly which effects should be re-executed when specific signals change. This approach ensures that only the necessary parts of your application update in response to state changes, resulting in more efficient rendering and overall better performance. Conclusion Effects in SolidJS are a powerful feature that enable you to react to changes in your application's state dynamically. By leveraging createEffect and using lifecycle functions like onMount and onCleanup, you can create robust and responsive applications. Understanding how to effectively use effects will help you build more efficient, maintainable, and bug-free SolidJS applications....

Storybook: Can Your Next Project Benefit from It? cover image

Storybook: Can Your Next Project Benefit from It?

I will show you what Storybook is all about and hopefully help you decide if you need it in your next project. Don't worry if you have limited experience as an engineer because you don't need to have an advanced technical background to make use of Storybook. What is Storybook? Storybook is a tool for developing UIs that allows you to work on one component at a time. What is a component? A component is smallest part of a UI. In chemistry, we refer to it as an atom(_Smallest unit of a matter_). Most frameworks are now components based. Why Storybook? Storybook allows you to actually develop the entire UIs without starting the major application. But in order to cleary state why one would choose to use it, lets look at some benefits and challenges of Storybook. Benefits - Being able to build components in isolation,and not having to think about integrations or other systems running in your stack is a blessing - A clearer vision of your components styling and layout - Navigating between UI component as you get to see all component as a sidebar item - Communicating with other devs. It really allows you to show how your new component is supposed to be used and which features it boasts. - You can manipulate props value - Its is not framework agnostic i.e you can use for Vue, React, Angular, etc. - Great for documenting Challenges - If you’re integrating it into an existing project, there is some migration work to be done. - You rely on addons and decorators for handling data. - It can take up a lot of time to maintain and properly set up. - It takes team commitment to keep it updated and ensure everything still works. What are add-ons actually? Add-ons are plugins that can be added to make certain feature work. For example, by default scss doesn't work on Storybook, so you will have to install an add-on to make it work as expected. When to use Storybook In this section, we will the making use of This Dot Labs' Open source project starter.dev as a case study. starter.dev is built using a variety of technologies to demonstrate architectural patterns and best practices using these tools. This project uses these technologies like Vue, React, Nextjs, Angular, etc to show various ways Github can be implemented!. Lets Pick a component from starter.dev GitHub Showcases to demonstrate the features Storybook has. Every conponent has a control tab that allows us to manipulte the props if there be any. For example: Here, looking at the image with the props, you will notice some properties: - cardType: This is a dropdown/select option with two opions issue and pullrequest. - state: this defines the state of the card - author: the person who created it or a name, or whatever, you get the point. Lets change some of the props and see the result - cardType will be pullrequest - state will be closed Here, we can see there has been a change. This is so helpful, and tells the team members what the component can and can't do. Other features Looking at other interesting features like - Settings Here, we can toggle for feature like side nav, the controls (which, in the dropdown option, is call addons) - Responsiveness There are few options that help us test for responsivess. Below, you will find an image showing those options: Here we can select any option to see the responsiveness of that component. Large screen Mobile screen Hover state of the card - Inspection Here, we can see certain properties like padding, and current width and height Looking to get started To get started, all you need is to visit this sites based on your prefered technology - Storybook with Vue - Storybook with React - Storybook with Angular - Storybook with Web Components - Storybook with Web Svelte - Storybook with Web Preact - Storybook with Web Ember Conclusion It's up to you to decide if Storybook helps you achieve your goals faster, or if you think it's useful for your project setup. It's important to look at what it could offer and what it can't. You can decide to use it for just plain documentation or for components, or both....

“Music and code have a lot in common,” freeCodeCamp’s Jessica Wilkins on what the tech community is doing right to onboard new software engineers cover image

“Music and code have a lot in common,” freeCodeCamp’s Jessica Wilkins on what the tech community is doing right to onboard new software engineers

Before she was a software developer at freeCodeCamp, Jessica Wilkins was a classically trained clarinetist performing across the country. Her days were filled with rehearsals, concerts, and teaching, and she hadn’t considered a tech career until the world changed in 2020. > “When the pandemic hit, most of my gigs were canceled,” she says. “I suddenly had time on my hands and an idea for a site I wanted to build.” That site, a tribute to Black musicians in classical and jazz music, turned into much more than a personal project. It opened the door to a whole new career where her creative instincts and curiosity could thrive just as much as they had in music. Now at freeCodeCamp, Jessica maintains and develops the very JavaScript curriculum that has helped her and millions of developers around the world. We spoke with Jessica about her advice for JavaScript learners, why musicians make great developers, and how inclusive communities are helping more women thrive in tech. Jessica’s Top 3 JavaScript Skill Picks for 2025 If you ask Jessica what it takes to succeed as a JavaScript developer in 2025, she won’t point you straight to the newest library or trend. Instead, she lists three skills that sound simple, but take real time to build: > “Learning how to ask questions and research when you get stuck. Learning how to read error messages. And having a strong foundation in the fundamentals” She says those skills don’t come from shortcuts or shiny tools. They come from building. > “Start with small projects and keep building,” she says. “Books like You Don’t Know JS help you understand the theory, but experience comes from writing and shipping code. You learn a lot by doing.” And don’t forget the people around you. > “Meetups and conferences are amazing,” she adds. “You’ll pick up things faster, get feedback, and make friends who are learning alongside you.” Why So Many Musicians End Up in Tech A musical past like Jessica’s isn’t unheard of in the JavaScript industry. In fact, she’s noticed a surprising number of musicians making the leap into software. > “I think it’s because music and code have a lot in common,” she says. “They both require creativity, pattern recognition, problem-solving… and you can really get into flow when you’re deep in either one.” That crossover between artistry and logic feels like home to people who’ve lived in both worlds. What the Tech Community Is Getting Right Jessica has seen both the challenges and the wins when it comes to supporting women in tech. > “There’s still a lot of toxicity in some corners,” she says. “But the communities that are doing it right—like Women Who Code, Women in Tech, and Virtual Coffee—create safe, supportive spaces to grow and share experiences.” She believes those spaces aren’t just helpful, but they’re essential. > “Having a network makes a huge difference, especially early in your career.” What’s Next for Jessica Wilkins? With a catalog of published articles, open-source projects under her belt, and a growing audience of devs following her journey, Jessica is just getting started. She’s still writing. Still mentoring. Still building. And still proving that creativity doesn’t stop at the orchestra pit—it just finds a new stage. Follow Jessica Wilkins on X and Linkedin to keep up with her work in tech, her musical roots, and whatever she’s building next. Sticker illustration by Jacob Ashley....

Let's innovate together!

We're ready to be your trusted technical partners in your digital innovation journey.

Whether it's modernization or custom software solutions, our team of experts can guide you through best practices and how to build scalable, performant software that lasts.

Prefer email? hi@thisdot.co