HelloJohn / docs
Quickstart

Quickstart — JavaScript

Add HelloJohn authentication to any JavaScript app — Vanilla JS, Svelte, SolidJS, Astro, or any framework not covered by a dedicated SDK.

Time: ~10 minutes Prerequisites: A HelloJohn account (Cloud) or a self-hosted server running locally.

Install the SDK

npm install @hellojohn/js
yarn add @hellojohn/js
pnpm add @hellojohn/js
<script src="https://cdn.hellojohn.dev/js/v1/hellojohn.min.js"></script>

Initialize the client

src/lib/hellojohn.ts
import { HelloJohn } from '@hellojohn/js'

export const hellojohn = new HelloJohn({
  publishableKey: 'pk_live_XXXXXXXXXXXXXXXX',
})

Only use your Publishable Key (pk_...) in browser code. Never include your Secret Key in client-side JavaScript.

Mount the sign-in form

Render the hosted sign-in UI into any DOM element:

src/pages/sign-in.ts
import { hellojohn } from '../lib/hellojohn'

const container = document.getElementById('sign-in-container')!

hellojohn.mountSignIn(container, {
  redirectUrl: '/dashboard',
})
sign-in.html
<div id="sign-in-container"></div>
<script type="module" src="/src/pages/sign-in.ts"></script>

Check if the user is signed in

src/pages/dashboard.ts
import { hellojohn } from '../lib/hellojohn'

async function init() {
  const session = await hellojohn.getSession()

  if (!session) {
    window.location.href = '/sign-in'
    return
  }

  const user = session.user
  document.getElementById('greeting')!.textContent = `Welcome, ${user.name}!`
}

init()

Listen for auth state changes

React to sign-in and sign-out events:

src/lib/auth-listener.ts
import { hellojohn } from './hellojohn'

hellojohn.addListener('session', (session) => {
  if (session) {
    console.log('Signed in:', session.user.email)
    showDashboard()
  } else {
    console.log('Signed out')
    showSignIn()
  }
})

Get the token for API calls

src/lib/api.ts
import { hellojohn } from './hellojohn'

export async function fetchWithAuth(url: string, init?: RequestInit) {
  const token = await hellojohn.getToken()

  return fetch(url, {
    ...init,
    headers: {
      ...init?.headers,
      Authorization: `Bearer ${token}`,
    },
  })
}

Using with Svelte, SolidJS, or Astro

The @hellojohn/js SDK is framework-agnostic. You can wrap it in your framework's reactive primitives:

src/stores/auth.ts (Svelte)
import { writable } from 'svelte/store'
import { hellojohn } from '$lib/hellojohn'

export const session = writable(null)

hellojohn.addListener('session', (s) => session.set(s))
src/stores/auth.ts (SolidJS)
import { createSignal } from 'solid-js'
import { hellojohn } from './hellojohn'

const [session, setSession] = createSignal(null)

hellojohn.addListener('session', setSession)

export { session }

Next steps

On this page