A Quick Tour
Let's create a blog backend on Loco in just a few minutes. First install `loco` and `sea-orm-cli`:
Now you can create your new app (choose "SaaS
app"). Select SaaS app with client side rendering:
)
You'll have:
sqlite
for database. Learn about database providers in Sqlite vs Postgres in the models section.async
for background workers. Learn about workers configuration async vs queue in the workers section.- client-side asset serving configuration. This means your backend will serve as API and will also serve your static client-side content.
Now cd
into your myapp
and start your app by running cargo loco start
:
Adding a CRUD API
We have a base SaaS app with user authentication generated for us. Let's make it a blog backend by adding a post
and a full CRUD API using scaffold
:
Because we're building a backend with a client-side codebase for the client, we'll build an API using --api
:
Your database have been migrated and model, entities, and a full CRUD controller have been generated automatically.
Start your app again:
If you want to use curl
to test the --html
scaffold, you will need to send your requests with the Content-Type application/x-www-form-urlencoded
and the body as title=Your+Title&content=Your+Content
by default. This can be changed to allow application/json
as a Content-Type
in the code if desired.
Next, try adding a post
with curl
:
You can list your posts:
For those counting -- the commands for creating a blog backend were:
cargo install loco
cargo install sea-orm-cli
loco new
cargo loco generate scaffold post title:string content:text --api
Done! enjoy your ride with loco
🚂
Checking Out SaaS Authentication
Your generated app contains a fully working authentication suite, based on JWTs.
Registering a New User
The /api/auth/register
endpoint creates a new user in the database with an email_verification_token
for account verification. A welcome email is sent to the user with a verification link.
For security reasons, if the user is already registered, no new user is created, and a 200 status is returned without exposing user email details.
Login
After registering a new user, use the following request to log in:
The response includes a JWT token for authentication, user ID, name, and verification status.
{
}
In your client-side app, you save this JWT token and make following requests with it using bearer token (see below) in order for those to be authenticated.
Get current user
This endpoint is protected by auth middleware. We will use the token we got earlier to perform a request with the bearer token technique (replace TOKEN
with the JWT token you got earlier):
That should be your first authenticated request!.
Check out the source code for controllers/auth.rs
to see how to use the authentication middleware in your own controllers.