Learn how to integrate Nile Auth with any JavaScript backend framework. This guide shows a quickstart example for Node.js to help you get started using the Nile Auth SDK with your backend. In full-stack applications, user signup, authentication and even user profile UI can be handled automatically by the built-in routes and UI components. However, depending on your application’s requirements, you may need to use the SDK to directly call user management APIs in Nile Auth. This quickstart example shows how to do this. For more details on the Nile Auth JavaScript SDK, see the Nile Auth JS SDK documentation.

It is important to note that the Auth service is designed to work with actions a user would take in the context of your B2b webapplication.

Quickstart

Nile SDK has APIs for working with users, tenants and sessions. In the example below, we’ll create a new user, login as that user, get and update the user’s profile information. We’ll then create a new tenant for that user, list users in the tenant and delete the tenant. Finally, we’ll show how to use the SDK to protect a route by checking if the user is authenticated and sign the user out.

1

Create a new NodeJS project

mkdir my-project
cd my-project
npm init -y
2

Install the Nile Auth SDK

npm install @niledatabase/server
3

Import and initialize the Nile Auth SDK

We’ll use a single file for the entire example. Create a new file called nile-qs.js and add the following code:

import { Nile } from '@niledatabase/server';

const nile = await Nile({
  // debug: true  // Enable detailed logging
});
4

Configure the Nile Auth SDK with your environment variables

The Nile object can be configured directly from environment variables, which you can get from Nile Console. Place them in a .env file in the root of your project.

NILEDB_USER=
NILEDB_PASSWORD=
NILEDB_API_URL=
NILEDB_POSTGRES_URL=
5

Create a new user

Let’s start by creating a new user, so we can use it for the rest of the example:

create
console.log("Creating user:");
const user = await nile.api.users.createUser({
    email: 'test@test.com',
    password: 'password'
});
6

Login a user with email and password

To login a user with email and password, you can use the following code:

login
try {
  const loginBody = {
      email: 'test@test.com',
      password: 'password'
  }
  console.info(`logging in using ${loginBody.email} ${loginBody.password}`);
  await nile.api.login(loginBody);
} catch (err) {
  console.error("Failed to login", err);
  process.exit(1);
}

This will set nile.api.headers to include the user’s session token and the CSRF token. These will automatically be added to all subsequent requests.

7

Get the user's profile information

Next, let’s get the user’s profile information by calling the me API:

me
console.log("Getting user's profile information:");
const me = await nile.api.users.me();
console.log(me);
8

Update a user's profile information

Update a user’s profile information by calling the update API:

update
console.log("Updating user's profile information:");
const update = {
  name: 'updatedName',
};
const updatedUser = await nile.api.users.updateMe(update);
console.log(updatedUser);
9

Create a new tenant

You can create a new tenant by calling the createTenant API:

create-tenant
console.log("Creating tenant:");
const tenant = await nile.api.tenants.createTenant({
    name: 'tenantName'
});
console.log(tenant);
Because we already authenticated as a user in a previous step, the new tenant will be linked to the user.
10

Update a tenant

You rename a tenant by calling the updateTenant API after setting the tenantId to the tenant you want to update:

update-tenant
console.log("Updating tenant:");
nile.tenantId = tenant.id; // `tenant` object is returned from the `tenants.create` call in the previous step
const updatedTenant = await nile.api.tenants.updateTenant({
    name: 'newTenantName'
});
console.log(updatedTenant);
11

List users in a tenant

You can list the users in a tenant by calling the listUsers API after setting the tenantId to the tenant you want to list users from:

list-users
nile.tenantId = tenant.id;
console.log("Listing users in a tenant:");
const users = await nile.api.users.listUsers();
console.log(users);
12

Delete a tenant

You can mark a tenant as deleted by calling the deleteTenant API after setting the tenantId to the tenant you want to delete:

delete-tenant
console.log("Deleting tenant:");
nile.tenantId = tenant.id; 
await nile.api.tenants.deleteTenant();
This does not delete the tenant or its data from the database, it soft-deletes the tenant by setting the deleted field to current timestamp.
13

Check if a user is authenticated

A key use case for the server-side SDK is to check if a user is authenticated before allowing them to access a resource:

check-auth
console.log("Checking if a user is authenticated:");
const session = await nile.api.auth.getSession();
if (!session) {
  // in real example, you would return a 401 Unauthorized error
  console.error('User is not authenticated');
  process.exit(1);
}

// in real example, you would allow the user to do something that only authenticated users can do
// and then return a 200 OK response and maybe some data
console.log('User is authenticated', session.user);
console.log('We can now allow them to do something that only authenticated users can do');
14

Sign out a user

Once we are done, we can sign out the user by calling the signOut API:

signOut
console.log("Signing out a user:");
const res = await nile.api.auth.signOut();
if (res.url) {
  // In real example, you would redirect the user to the URL in the response
  console.log('Redirect to:', res.url);
}
15

Run the example

To see the example in action, run the following command:

node nile-qs.js

Security Considerations

  • Never log or otherwise store user passwords in plain text
  • Never log or store authentication tokens or session information
  • Always validate and sanitize user input before passing it to Nile Auth APIs
  • Avoid exposing detailed error messages to clients that might reveal system information
  • Implement rate limiting for authentication attempts to prevent brute force attacks
  • Log authentication failures and suspicious activities for monitoring
  • Implement appropriate error responses that don’t leak sensitive information
  • Keep your Nile SDK and dependencies up to date

For more information and examples

Best Practices

  1. Error Handling Implement comprehensive error handling for all authentication flows. Return user-friendly error messages while logging detailed errors server-side. Use try-catch blocks around all authentication operations.

  2. Session Management Regularly validate sessions. Implement proper session cleanup on logout. Use secure session storage methods.

  3. Code Organization Separate authentication logic into dedicated middleware. Create reusable authentication utilities. Keep configuration in environment variables.

  4. Testing Test authentication flows thoroughly. Include both success and failure scenarios. Mock external authentication providers in tests.

Troubleshooting

Common Issues

  1. Invalid Session Token Verify that user authentication was successful. Verify the token is being properly passed in requests. Check if the session has expired. Ensure the token format is correct.

  2. CORS Issues Ensure your server is configured to accept requests from your client domain. Check that necessary CORS headers are being set.

  3. User Creation Failures Make sure you properly handle common user mistakes: Validate email format before submission and check for duplicate email address error that may be returned.

Debug Tips

  1. Enable debug logging:
const nile = new Nile({
  debug: true  // Enable detailed logging
});
  1. Monitor network requests in your browser’s developer tools
  2. Check server logs for detailed error messages
  3. Verify environment variables are properly set

For additional support, visit our Discord community or GitHub discussions.

Was this page helpful?