API Reference

This documentation explains how to use your generated backend API based on your database schema.

Install

Install the npm package:

npm install thin-backend

Initialize

Call initThinBackend before starting your app:

import { initThinBackend, ensureIsUser } from 'thin-backend';

// This needs to be run before any calls to `query`, `createRecord`, etc.
initThinBackend({
    host: 'https://# Log into Thin Backend and get the BACKEND_URL from the project settings'
});

// Start the React app
ReactDOM.render(<App/>, document.getElementById('app'));

Authentication

Get the current User

Use getCurrentUser() to access the current user object.

If the user is not logged in, this will return null.

JavaScript
const user = getCurrentUser();

let email = user.email;
let name = user.name;
user
{
    "id": "334a2050-5720-4cb9-82b2-efdf7009bac7",
    "email": "jon@snow.com"
}
function UserDetails() {
    const user = useCurrentUser();

    return <div>{user.email}</div>;
}
function UserDetails() {
    const user = useCurrentUser();

    return <div>{user.email}</div>;
}
Request
curl https://<thin-backend-url>/api/user \
    -H "Accept: application/json" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer: <ihp_backend_jwt>"
Response
{
    "id": "334a2050-5720-4cb9-82b2-efdf7009bac7",
    "email": "jon@snow.com"
}

loginWithRedirect()

Useful to implement a login button. Redirects the user to the login page.

The returned promise never resolves, as the browser is redirected to a different page.

import { loginWithRedirect } from 'thin-backend';

await loginWithRedirect();
import { loginWithRedirect } from 'thin-backend';

function LoginButton() {
    const isLoading = useState(false);

    async function doLogin() {
        setLoading(true);
        await loginWithRedirect();
        setLoading(false);
    }

    return <button onClick={doLogin} disabled={isLoading}>Login</button>
}
import { loginWithRedirect } from 'thin-backend';

function LoginButton() {
    const isLoading = useState(false);

    async function doLogin() {
        setLoading(true);
        await loginWithRedirect();
        setLoading(false);
    }

    return <button onClick={doLogin} disabled={isLoading}>Login</button>
}

logout()

Removes the JWT from the localStorage and redirects the user to the login page.
import { logout } from 'thin-backend';

// Logout and redirect to login page
await logout();

// Logout and redirect to https://example.com
await logout({ redirect: 'https://example.com' })
function LogoutButton() {
    const isLoading = useState(false);

    async function doLogout() {
        setLoading(true);
        await logout();
        setLoading(false);
    }

    return <button onClick={doLogout} disabled={isLoading}>Logout</button>
}
function LogoutButton() {
    const isLoading = useState(false);

    async function doLogout() {
        setLoading(true);
        await logout();
        setLoading(false);
    }

    return <button onClick={doLogout} disabled={isLoading}>Logout</button>
}

<ThinBackend />

This react component provides the AuthCompletedContext context.

Internally it calls initAuth() to provide the current user to the application and to handle redirects from the login page.

If you pass requireLogin, like <ThinBackend requireLogin/>, it will call ensureIsUser() to trigger a redirect to the login page if the user is not logged in yet.

import { ThinBackend } from 'thin-backend-react';

// React entrypoint component
function App() {
    // The `requireLogin` triggers a redirect to the login page if not logged in already
    return <ThinBackend>
        <div>Hello World</div>
    </ThinBackend>
}


// Start the React app
ReactDOM.render(<App/>, document.getElementById('app'));

initAuth()

Should be called at the start of your application before any query calls.

This function checks if there's a current JWT in the localStorage and then prepares the state for functions such as getCurrentUserId() to work.

If the user was redirect to the app from the login page, this function will trade the received access token to a full JWT, and then save it to the localStorage.

If you use react, use <ThinBackend/> instead. Internally it calls initAuth().

If the user is logged out, this function does not do anything. See ensureIsUser(), which is a variant of initAuth() but redirects to the login page if there's no user session.

import { initAuth } from 'thin-backend';

// Called before any query logic below:
await initAuth();

// This call is authenticated now:
const tasks = await query('tasks').fetch();

DataSubscription

The DataSubscription API provides a realtime interface to retrieve results for database queries and automatically refresh when the underlying data has changed. Higher-level APIs like useQuery are built on top of DataSubscription.

import { DataSubscription } from 'thin-backend';

const queryBuilder = query('tasks').orderBy('createdAt');

// Create a new subscription
const tasksSubscription = new DataSubscription(queryBuilder.query);

// Retrieve data, and set up database listener
tasksSubscription.createOnServer();

const unsubscribe = tasksSubscription.subscribe(tasks => {
    // This callback is called on initial data fetch
    // and then called whenever the result set is updated

    console.log('Tasks updated', tasks);
});

// When you're done with the subscription, remove the listener
// The `DataSubscription` will calls it's own `.close()` method
// when there's no subscribers anymore.
unsubscribe();