Magic Link authentication provides a passwordless sign-in experience where users receive a secure link via email to authenticate. This method eliminates the need for passwords while maintaining security.

Overview

Magic Link authentication flow:

  1. User enters their email address
  2. They receive a secure link with an authentication token via email. The token is valid for 4 hours by default and is saved in the auth.verification_tokens table in your database.
  3. Clicking the link automatically exchanges the token for a session, logs them into your application and redirects them to the callbackUrl configured in the sign component.

Implementation Steps

1

Obtain Database Credentials

  1. If you haven’t signed up for Nile yet, sign up here and follow the steps to create a database.
  2. Navigate to Database Settings in your database’s UI at console.thenile.dev.
  3. Go to Connection settings.
  4. Select the CLI icon, and click Generate credentials
  5. Copy the required credentials and store them in an .env file so they can be used in the application to connect to the Nile auth service.
    NILEDB_USER=niledb_user
    NILEDB_PASSWORD=niledb_password
    NILEDB_API_URL=https://us-west-2.api.thenile.dev/v2/databases/<database_id>
    NILEDB_POSTGRES_URL=postgres://us-west-2.db.thenile.dev:5432/<database_name>
    
2

Configure Email Settings

Ensure you have configured your email settings in the Nile Dashboard. You’ll need a valid SMTP provider configured to send emails from your application, and email templates configured for the magic link.

3

Run create-next-app

This guide uses Next.js with App Router, Typescript and Tailwind CSS. If you have a different framework in mind, you can find additional guides under “Frameworks” in the sidebar. Initialize a new Next.js project with the following command and give it a name:

npx create-next-app@latest nile-app --yes
4

Install dependencies

npm install @niledatabase/server @niledatabase/react
5

Your application must expose API routes to handle authentication operations.

First, create a folder called api under the app folder and a folder called [...nile] under it:

mkdir -p app/api/\[...nile\]

Create following files handle the calls to your server, as well as expose the nile instance to your application:

/api/[...nile]/nile.ts

import { Nile } from "@niledatabase/server";
export const nile = await Nile();
export const { handlers } = nile.api;

/api/[...nile]/route.ts

import { handlers } from "./nile";
export const { POST, GET, DELETE, PUT } = handlers;
6

Frontend Implementation

The <EmailSignIn /> component is used to send a magic link to the user’s email address.

Was this page helpful?