Add user login to a static site

Sign-up, login and members-only content for a plain HTML site on GitHub Pages, Netlify or Vercel, without running an auth server.

CodeFreeAPI Team
3 min read

Static sites are fast, cheap and easy to host, until you need "only members can see this". Normally that means adding a server for sessions and passwords. Here you'll add sign-up and login to a plain HTML page with a few lines of JavaScript, using CodeFreeAPI as the backend.

1. Set up the project

  1. Create a free account and a new project at codefreeapi.com. Every project has a users entity that stores accounts; passwords are hashed for you.
  2. Add an entity notes with a text field content, and set all its methods to Signed-in users (or Only the record's owner for private notes).
  3. Create a publishable API key that can read and create notes. Sign-up and login always work with it.

2. The page

<!doctype html>
<html>
<body>
  <section id="signed-out">
    <h2>Sign in</h2>
    <form id="auth">
      <input id="email" type="email" placeholder="Email" required />
      <input id="password" type="password" placeholder="Password (6+ characters)" required />
      <button name="action" value="login">Sign in</button>
      <button name="action" value="register">Create account</button>
    </form>
    <p id="error"></p>
  </section>

  <section id="signed-in" hidden>
    <p>Hello, <span id="who"></span> <button id="logout">Sign out</button></p>
    <ul id="notes"></ul>
  </section>

  <script src="app.js"></script>
</body>
</html>

3. The script

const API = 'https://YOUR_PROJECT.codefreeapi.com/api/v1';
const KEY = 'YOUR_PUBLISHABLE_KEY';
let session = JSON.parse(localStorage.getItem('session') || 'null');

async function api(path, options = {}) {
  const headers = { 'X-API-Key': KEY, 'Content-Type': 'application/json' };
  if (session) headers.Authorization = `Bearer ${session.accessToken}`;
  let res = await fetch(API + path, { ...options, headers });
  // Access tokens last 15 minutes: swap the refresh token for new ones once
  if (res.status === 401 && session) {
    const refreshed = await fetch(`${API}/auth/refresh`, {
      method: 'POST',
      headers: { 'X-API-Key': KEY, 'Content-Type': 'application/json' },
      body: JSON.stringify({ refreshToken: session.refreshToken }),
    });
    if (!refreshed.ok) return signOut();
    save(await refreshed.json());
    headers.Authorization = `Bearer ${session.accessToken}`;
    res = await fetch(API + path, { ...options, headers });
  }
  return res;
}

function save(data) {
  session = { accessToken: data.accessToken, refreshToken: data.refreshToken };
  localStorage.setItem('session', JSON.stringify(session));
}

function signOut() {
  session = null;
  localStorage.removeItem('session');
  render();
}

document.getElementById('auth').addEventListener('submit', async (e) => {
  e.preventDefault();
  const action = e.submitter.value; // "login" or "register"
  const res = await api(`/auth/${action}`, {
    method: 'POST',
    body: JSON.stringify({ email: email.value, password: password.value }),
  });
  const body = await res.json();
  if (!res.ok) return (document.getElementById('error').textContent = body.error);
  save(body);
  render();
});

document.getElementById('logout').addEventListener('click', signOut);

async function render() {
  document.getElementById('signed-out').hidden = !!session;
  document.getElementById('signed-in').hidden = !session;
  if (!session) return;
  const me = await (await api('/auth/me')).json();
  document.getElementById('who').textContent = me.user.email;
  const notes = await (await api('/notes')).json();
  document.getElementById('notes').innerHTML = notes.data.map((n) => `<li>${n.content}</li>`).join('');
}

render();

What you get

  • Accounts with hashed passwords, and sign-in that survives page reloads.
  • /notes answers 401 to visitors who aren't signed in, so the content is protected on the server, not just hidden in the page.
  • With Only the record's owner, each member sees their own notes.

Extras worth switching on

  • Forgotten passwords: call POST /auth/forgot-password with the email; we send a reset link to a hosted page, or to your own page if you set one in Project Settings.
  • Confirmed emails: turn on Require email confirmation in Project Settings → User accounts.
  • Admins: promote a user to admin in the dashboard, and give admin-only rules to the things only you should change.

No server, no session store, no password hashing code: the static site stays static.

Build it on a real backend

Database, REST API, user login and logic, hosted for you. Free plan, no credit card; your API is live in a few minutes.