---
title: Connect a customer from your own sign-in
description: Build a small web app that links a person who is signed in to your site with a Nurish'd meals customer, so your server can order for them.
section: Tutorials
order: 2
---

# Connect a customer from your own sign-in

You will build a small web app. It sends a signed-in person to a Nurish'd page to approve, checks the answer when they come back, and remembers that they are connected.

## Single sign-on and the account link

Nurish'd Connect has no SAML or OpenID single sign-on. It has an account link instead. Your site already knows who is signed in. You create a Nurish'd customer under your own id for that person, and you send them once to a Nurish'd page to approve. They come back to your site. After that your server acts for them with the API, and they never sign in to Nurish'd on your site.

This is how the pieces map to what you know from single sign-on:

| In single sign-on              | In Nurish'd Connect                       |
| ------------------------------ | ----------------------------------------- |
| Your user id                   | `external_id`, your own id for the person |
| The consent screen             | The page at `connect_url`, shown once     |
| The redirect back to your site | Your `return_url`                         |
| A valid session                | A connection with the status `active`     |

A customer is a person you place meal orders for. The connection is their consent.

## Before you start

- You finished [Set up your project](/docs/tutorials/set-up-your-project). Your project has the `nurishd` client file and a Sandbox key in `NURISHD_API_KEY`.
- Your key has the scopes `order:write` and `order:read`. They are needed to create a customer and to read the connection. Run `check_key` from the setup tutorial to see your scopes.
- A return URL is the address Nurish'd sends the person back to. It must start with `https://` and be registered in the console. Step 1 shows how to get one while you build.
- Install the web server package for your language.

| Language   | Command                                                                  |
| ---------- | ------------------------------------------------------------------------ |
| Python     | `pip install flask`                                                      |
| JavaScript | `npm install express`                                                    |
| TypeScript | `npm install express` and `npm install --save-dev @types/express`        |
| Java       | Replace `pom.xml` with the one below. It adds Javalin and a log package. |

## 1. Get a public address and register the return URL

Nurish'd cannot send the browser back to `localhost`. While you build, a tunnel tool gives your computer a public HTTPS address that forwards to your server. Two common ones are ngrok and Cloudflare Tunnel. Follow their own setup guides, then start a tunnel to port 3000.

- ngrok: `ngrok http 3000`
- Cloudflare Tunnel: `cloudflared tunnel --url http://localhost:3000`

The tool prints an address such as `https://example-name.trycloudflare.com`. Your return URL is that address plus `/nurishd/return`. Leave the tunnel running.

Register the return URL in the console. See [Company settings](/docs/console/company-settings). A return URL that does not start with `https://` or is not on the list answers `422 validation_error`.

The program reads the return URL from the `NURISHD_RETURN_URL` environment variable. Set it in the terminal where you run the program. Use your own address.

- macOS and Linux: `export NURISHD_RETURN_URL="https://example-name.trycloudflare.com/nurishd/return"`
- Windows PowerShell: `$env:NURISHD_RETURN_URL = "https://example-name.trycloudflare.com/nurishd/return"`

## 2. Add a stand-in for your sign-in

This tutorial is about Nurish'd, so it does not build a sign-in. The program has one fixed signed-in user. A real app takes this user from its session.

The `id` is your own id for the person. It becomes the `external_id`. The program also keeps what it learns about each user in memory. A real app uses its database.

```python
app = Flask(__name__)

# The return URL you registered in the console. It starts with https://.
RETURN_URL = os.environ.get("NURISHD_RETURN_URL")
if not RETURN_URL:
    raise SystemExit("Set NURISHD_RETURN_URL first.")

# Stands in for your own sign-in. A real app reads this from its session.
SIGNED_IN_USER = {
    "id": "customer-1001",
    "email": "ada.lovelace@example.com",
    "first_name": "Ada",
    "last_name": "Lovelace",
}

# What we know about each user's link, by user id. A real app uses its database.
links = {}

# A connection id goes into a URL path, so check its shape before you use it.
CONNECTION_ID = re.compile(r"[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}")
```

```javascript
const app = express();

// The return URL you registered in the console. It starts with https://.
const RETURN_URL = process.env.NURISHD_RETURN_URL ?? '';
if (!RETURN_URL) throw new Error('Set NURISHD_RETURN_URL first.');

// Stands in for your own sign-in. A real app reads this from its session.
const signedInUser = {
	id: 'customer-1001',
	email: 'ada.lovelace@example.com',
	firstName: 'Ada',
	lastName: 'Lovelace',
};

// What we know about each user's link, by user id. A real app uses its database.
const links = new Map();

// A connection id goes into a URL path, so check its shape before you use it.
const CONNECTION_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/;
```

```typescript
const app = express();

// The return URL you registered in the console. It starts with https://.
const RETURN_URL = process.env.NURISHD_RETURN_URL ?? '';
if (!RETURN_URL) throw new Error('Set NURISHD_RETURN_URL first.');

// Stands in for your own sign-in. A real app reads this from its session.
const signedInUser = {
	id: 'customer-1001',
	email: 'ada.lovelace@example.com',
	firstName: 'Ada',
	lastName: 'Lovelace',
};

// What we know about each user's link, by user id. A real app uses its database.
const links = new Map<string, Link>();

// A connection id goes into a URL path, so check its shape before you use it.
const CONNECTION_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/;
```

```java
    // The return URL you registered in the console. It starts with https://.
    static final String RETURN_URL = System.getenv("NURISHD_RETURN_URL");

    // Stands in for your own sign-in. A real app reads this from its session.
    static final String USER_ID = "customer-1001";
    static final String EMAIL = "ada.lovelace@example.com";
    static final String FIRST_NAME = "Ada";
    static final String LAST_NAME = "Lovelace";

    // What we know about a user's link.
    record Link(String customerId, String connectionId, boolean connected) {}

    // The links by user id. A real app uses its database.
    static final Map<String, Link> links = new HashMap<>();

    // A connection id goes into a URL path, so check its shape before you use it.
    static final Pattern CONNECTION_ID = Pattern.compile("[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}");
```

`RETURN_URL` is the address you registered. The program stops with a message when `NURISHD_RETURN_URL` is not set. `CONNECTION_ID` is a check for step 5.

## 3. Turn a refusal into words

Two answers of `POST /meals/v1/customer/create/document` are `409` refusals. Nothing is created. Each one needs a different message for the person.

| Code                       | What it means                                                         | What to tell the person                                       |
| -------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------- |
| `external_id_conflict`     | Your id already belongs to a customer with a different email.         | Their email changed. Ask them to contact your support.        |
| `person_already_connected` | This email is already connected to your company under a different id. | They have another account with you. Ask them to use that one. |

Keep using the first `external_id` of a person. Do not make a new one.

The helper `page` sends a small HTML answer. The helper `explain` picks the message. Any other error is printed for you, and the person sees a general message.

```python
def page(text, status=200):
    return f"<p>{text}</p>", status


def explain(error):
    if error.code == "external_id_conflict":
        return page("Your email changed. Contact support so we can fix the link.", 409)
    if error.code == "person_already_connected":
        return page("This email is already linked to another account. Sign in to that account.", 409)
    print(error)
    return page("We could not start the link. Try again later.", 502)
```

```javascript
function page(res, text, status = 200) {
	res.status(status).send(`<p>${text}</p>`);
}

function explain(res, error) {
	if (error.code === 'external_id_conflict') {
		return page(
			res,
			'Your email changed. Contact support so we can fix the link.',
			409,
		);
	}
	if (error.code === 'person_already_connected') {
		return page(
			res,
			'This email is already linked to another account. Sign in to that account.',
			409,
		);
	}
	console.log(error.message);
	return page(res, 'We could not start the link. Try again later.', 502);
}
```

```typescript
function page(res: Response, text: string, status = 200) {
	res.status(status).send(`<p>${text}</p>`);
}

function explain(res: Response, error: NurishdError) {
	if (error.code === 'external_id_conflict') {
		return page(
			res,
			'Your email changed. Contact support so we can fix the link.',
			409,
		);
	}
	if (error.code === 'person_already_connected') {
		return page(
			res,
			'This email is already linked to another account. Sign in to that account.',
			409,
		);
	}
	console.log(error.message);
	return page(res, 'We could not start the link. Try again later.', 502);
}
```

```java
    static void page(Context ctx, String text, int status) {
        ctx.status(status).html("<p>" + text + "</p>");
    }

    static void explain(Context ctx, NurishdException error) {
        if (error.code.equals("external_id_conflict")) {
            page(ctx, "Your email changed. Contact support so we can fix the link.", 409);
        } else if (error.code.equals("person_already_connected")) {
            page(ctx, "This email is already linked to another account. Sign in to that account.", 409);
        } else {
            System.out.println(error.getMessage());
            page(ctx, "We could not start the link. Try again later.", 502);
        }
    }
```

## 4. Start the link

`GET /nurishd/connect` runs when the person presses a "Connect Nurish'd" button on your site. It calls `POST /meals/v1/customer/create/document` with the person's details and your `return_url`.

The answer has three things you use:

- `user` is the id of the customer. You use it later to place orders.
- `connection.connection_id` is the id of the connection.
- `connect_url` is the Nurish'd page where the person approves.

The route stores the first two for this user and redirects the browser to `connect_url`. Open the link as a full page. Never put it in a frame or a web view, because the page refuses to load there.

The link works once and for 24 hours. If the person waits too long, call create again with the same `external_id`. You get the same customer and a fresh link.

`connect_url` is `null` when the person does not need to approve now. The route then goes straight to `/me`.

```python
@app.get("/nurishd/connect")
def connect():
    user = SIGNED_IN_USER
    try:
        customer = call(
            "POST",
            "/meals/v1/customer/create/document",
            body={
                "external_id": user["id"],
                "email": user["email"],
                "first_name": user["first_name"],
                "last_name": user["last_name"],
                "return_url": RETURN_URL,
            },
        )
    except NurishdError as error:
        return explain(error)
    connection = customer["connection"]
    links[user["id"]] = {
        "customer_id": customer["user"],
        "connection_id": connection["connection_id"],
        "connected": connection["status"] == "active",
    }
    if customer["connect_url"] is None:
        return redirect("/me")
    return redirect(customer["connect_url"])
```

```javascript
app.get('/nurishd/connect', async (req, res) => {
	const user = signedInUser;
	let customer;
	try {
		customer = await call('POST', '/meals/v1/customer/create/document', {
			body: {
				external_id: user.id,
				email: user.email,
				first_name: user.firstName,
				last_name: user.lastName,
				return_url: RETURN_URL,
			},
		});
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		return explain(res, error);
	}
	links.set(user.id, {
		customerId: customer.user,
		connectionId: customer.connection.connection_id,
		connected: customer.connection.status === 'active',
	});
	if (customer.connect_url === null) return res.redirect('/me');
	res.redirect(customer.connect_url);
});
```

```typescript
app.get('/nurishd/connect', async (req, res) => {
	const user = signedInUser;
	let customer: Customer;
	try {
		customer = await call<Customer>(
			'POST',
			'/meals/v1/customer/create/document',
			{
				body: {
					external_id: user.id,
					email: user.email,
					first_name: user.firstName,
					last_name: user.lastName,
					return_url: RETURN_URL,
				},
			},
		);
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		return explain(res, error);
	}
	links.set(user.id, {
		customerId: customer.user,
		connectionId: customer.connection.connection_id,
		connected: customer.connection.status === 'active',
	});
	if (customer.connect_url === null) return res.redirect('/me');
	res.redirect(customer.connect_url);
});
```

```java
    static void connect(Context ctx) {
        JsonNode customer;
        try {
            customer = Nurishd.call(
                    "POST",
                    "/meals/v1/customer/create/document",
                    Map.of(),
                    Map.of(
                            "external_id", USER_ID,
                            "email", EMAIL,
                            "first_name", FIRST_NAME,
                            "last_name", LAST_NAME,
                            "return_url", RETURN_URL));
        } catch (NurishdException error) {
            explain(ctx, error);
            return;
        }
        JsonNode connection = customer.path("connection");
        links.put(USER_ID, new Link(
                customer.path("user").asText(),
                connection.path("connection_id").asText(),
                connection.path("status").asText().equals("active")));
        if (customer.path("connect_url").isNull()) {
            ctx.redirect("/me");
        } else {
            ctx.redirect(customer.path("connect_url").asText());
        }
    }
```

## 5. Handle the return

The person approves on the Nurish'd page. Then Nurish'd sends the browser to your `return_url` with `connection_id` and `status` in the query, for example `/nurishd/return?connection_id=connection-0001&status=approved`.

Never trust that `status`. Anyone can type a URL. The route does three checks instead:

1. It checks the shape of `connection_id`, because the id goes into a URL path.
2. It reads the connection with `GET /meals/v1/connection/{connection_id}/get/document`. The answer comes from Nurish'd, so you can trust it.
3. It checks that the connection's `external_id` is the signed-in user's id. This refuses a person who pastes the id of someone else's connection.

Only then does it look at the `status` of the connection it read. The connection has one of four statuses:

| Status     | The page says                  |
| ---------- | ------------------------------ |
| `active`   | The person is connected.       |
| `pending`  | Not approved yet. Start again. |
| `declined` | The person declined.           |
| `revoked`  | The link ended. Start again.   |

Only `active` marks the user as connected.

```python
@app.get("/nurishd/return")
def come_back():
    user = SIGNED_IN_USER
    connection_id = request.args.get("connection_id", "")
    if not CONNECTION_ID.fullmatch(connection_id):
        return page("This link is not valid.", 400)
    try:
        connection = call("GET", f"/meals/v1/connection/{connection_id}/get/document")
    except NurishdError as error:
        if error.status == 404:
            return page("We do not know this connection.", 404)
        print(error)
        return page("We could not check the connection.", 502)
    if connection["external_id"] != user["id"]:
        return page("This connection belongs to someone else.", 403)
    if connection["status"] == "active":
        links[user["id"]] = {
            "customer_id": connection["user"],
            "connection_id": connection["connection_id"],
            "connected": True,
        }
        return page("You are connected to Nurish'd.")
    if connection["status"] == "pending":
        return page("Not approved yet. Go to /nurishd/connect for a new link.")
    if connection["status"] == "declined":
        return page("You declined the link. Go to /nurishd/connect to start again.")
    return page("The link ended. Go to /nurishd/connect to start again.")
```

```javascript
app.get('/nurishd/return', async (req, res) => {
	const user = signedInUser;
	const connectionId = String(req.query.connection_id ?? '');
	if (!CONNECTION_ID.test(connectionId)) {
		return page(res, 'This link is not valid.', 400);
	}
	let connection;
	try {
		connection = await call(
			'GET',
			`/meals/v1/connection/${connectionId}/get/document`,
		);
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		if (error.status === 404) {
			return page(res, 'We do not know this connection.', 404);
		}
		console.log(error.message);
		return page(res, 'We could not check the connection.', 502);
	}
	if (connection.external_id !== user.id) {
		return page(res, 'This connection belongs to someone else.', 403);
	}
	if (connection.status === 'active') {
		links.set(user.id, {
			customerId: connection.user,
			connectionId: connection.connection_id,
			connected: true,
		});
		return page(res, "You are connected to Nurish'd.");
	}
	if (connection.status === 'pending') {
		return page(
			res,
			'Not approved yet. Go to /nurishd/connect for a new link.',
		);
	}
	if (connection.status === 'declined') {
		return page(
			res,
			'You declined the link. Go to /nurishd/connect to start again.',
		);
	}
	page(res, 'The link ended. Go to /nurishd/connect to start again.');
});
```

```typescript
app.get('/nurishd/return', async (req, res) => {
	const user = signedInUser;
	const connectionId = String(req.query.connection_id ?? '');
	if (!CONNECTION_ID.test(connectionId)) {
		return page(res, 'This link is not valid.', 400);
	}
	let connection: Connection;
	try {
		connection = await call<Connection>(
			'GET',
			`/meals/v1/connection/${connectionId}/get/document`,
		);
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		if (error.status === 404) {
			return page(res, 'We do not know this connection.', 404);
		}
		console.log(error.message);
		return page(res, 'We could not check the connection.', 502);
	}
	if (connection.external_id !== user.id) {
		return page(res, 'This connection belongs to someone else.', 403);
	}
	if (connection.status === 'active') {
		links.set(user.id, {
			customerId: connection.user,
			connectionId: connection.connection_id,
			connected: true,
		});
		return page(res, "You are connected to Nurish'd.");
	}
	if (connection.status === 'pending') {
		return page(
			res,
			'Not approved yet. Go to /nurishd/connect for a new link.',
		);
	}
	if (connection.status === 'declined') {
		return page(
			res,
			'You declined the link. Go to /nurishd/connect to start again.',
		);
	}
	page(res, 'The link ended. Go to /nurishd/connect to start again.');
});
```

```java
    static void comeBack(Context ctx) {
        String connectionId = ctx.queryParamAsClass("connection_id", String.class).getOrDefault("");
        if (!CONNECTION_ID.matcher(connectionId).matches()) {
            page(ctx, "This link is not valid.", 400);
            return;
        }
        JsonNode connection;
        try {
            connection = Nurishd.call("GET", "/meals/v1/connection/%s/get/document".formatted(connectionId));
        } catch (NurishdException error) {
            if (error.status == 404) {
                page(ctx, "We do not know this connection.", 404);
                return;
            }
            System.out.println(error.getMessage());
            page(ctx, "We could not check the connection.", 502);
            return;
        }
        if (!connection.path("external_id").asText().equals(USER_ID)) {
            page(ctx, "This connection belongs to someone else.", 403);
            return;
        }
        String status = connection.path("status").asText();
        if (status.equals("active")) {
            links.put(USER_ID, new Link(
                    connection.path("user").asText(),
                    connection.path("connection_id").asText(),
                    true));
            page(ctx, "You are connected to Nurish'd.", 200);
        } else if (status.equals("pending")) {
            page(ctx, "Not approved yet. Go to /nurishd/connect for a new link.", 200);
        } else if (status.equals("declined")) {
            page(ctx, "You declined the link. Go to /nurishd/connect to start again.", 200);
        } else {
            page(ctx, "The link ended. Go to /nurishd/connect to start again.", 200);
        }
    }
```

## 6. Show the state

`GET /me` answers from what the program stored. After this, your pages and your order code check this state before they act for the person.

The last lines start the server on port 3000.

```python
@app.get("/me")
def me():
    user = SIGNED_IN_USER
    if links.get(user["id"], {}).get("connected"):
        return page(f"{user['first_name']}, you are connected to Nurish'd.")
    return page(f"{user['first_name']}, you are not connected yet. Go to /nurishd/connect.")


app.run(port=3000)
```

```javascript
app.get('/me', (req, res) => {
	const user = signedInUser;
	if (links.get(user.id)?.connected) {
		return page(res, `${user.firstName}, you are connected to Nurish'd.`);
	}
	page(
		res,
		`${user.firstName}, you are not connected yet. Go to /nurishd/connect.`,
	);
});

app.listen(3000, () => console.log('Listening on http://localhost:3000'));
```

```typescript
app.get('/me', (req, res) => {
	const user = signedInUser;
	if (links.get(user.id)?.connected) {
		return page(res, `${user.firstName}, you are connected to Nurish'd.`);
	}
	page(
		res,
		`${user.firstName}, you are not connected yet. Go to /nurishd/connect.`,
	);
});

app.listen(3000, () => console.log('Listening on http://localhost:3000'));
```

```java
    static void me(Context ctx) {
        Link link = links.get(USER_ID);
        if (link != null && link.connected()) {
            page(ctx, FIRST_NAME + ", you are connected to Nurish'd.", 200);
        } else {
            page(ctx, FIRST_NAME + ", you are not connected yet. Go to /nurishd/connect.", 200);
        }
    }

    public static void main(String[] args) {
        if (RETURN_URL == null || RETURN_URL.isBlank()) {
            System.out.println("Set NURISHD_RETURN_URL first.");
            System.exit(1);
        }
        Javalin app = Javalin.create();
        app.get("/nurishd/connect", Connect::connect);
        app.get("/nurishd/return", Connect::comeBack);
        app.get("/me", Connect::me);
        app.start(3000);
    }
}
```

## 7. Run it

Start the server.

| Language   | Command                                                      |
| ---------- | ------------------------------------------------------------ |
| Python     | `python connect.py`                                          |
| JavaScript | `node connect.js`                                            |
| TypeScript | `node connect.ts`                                            |
| Java       | `mvn -q compile exec:java -Dexec.mainClass=tutorial.Connect` |

Open your tunnel address in a browser, for example `https://example-name.trycloudflare.com/me`. It says you are not connected. Then open `https://example-name.trycloudflare.com/nurishd/connect`. The browser goes to the Nurish'd page. Use the tunnel address and not `localhost`, because Nurish'd sends the browser back to the address you registered.

In the Sandbox, no email is sent. The approval page accepts the code `424242`. See [Environments](/docs/get-started/environments). After you approve, the browser lands on `/nurishd/return` and the page says you are connected. Open `/me` again to see the stored state.

To see the redirect without a browser, ask your server for the route with `curl` on `localhost`.

```bash
curl -i http://localhost:3000/nurishd/connect
```

Among the headers you see the status `302` and a `Location` header. It holds the `connect_url` of your customer.

```text
HTTP/1.1 302 Found
Location: https://connect.example.com/approve/8f3k2m9q7x4z
```

Now call the return route with the connection id the create call answered. Then call it with an id that does not exist.

```bash
curl -i "http://localhost:3000/nurishd/return?connection_id=connection-0001&status=approved"
curl -i "http://localhost:3000/nurishd/return?connection_id=missing-1&status=approved"
```

```text
HTTP/1.1 200 OK
<p>You are connected to Nurish'd.</p>

HTTP/1.1 404 Not Found
<p>We do not know this connection.</p>
```

## The same for a care patient

The flow for a care patient is the same. You call `POST /care/v1/patient/create/document` and read the connection with `GET /care/v1/connection/{connection_id}/get/document`. A patient also needs a date of birth and an address. See [Connecting a patient](/docs/care/connecting-a-patient). To use a connected patient, follow [Book a dietitian visit](/docs/tutorials/book-a-dietitian-visit).

## Do not wait for the browser

The person may close the tab before they return to your site. The `connection.approved` event tells your server the same thing without the browser. See [Receive order webhooks](/docs/tutorials/receive-order-webhooks) and [Events](/docs/events/events).

## The whole program

```python
# file: connect.py
import os
import re

from flask import Flask, redirect, request

from nurishd import NurishdError, call

app = Flask(__name__)

# The return URL you registered in the console. It starts with https://.
RETURN_URL = os.environ.get("NURISHD_RETURN_URL")
if not RETURN_URL:
    raise SystemExit("Set NURISHD_RETURN_URL first.")

# Stands in for your own sign-in. A real app reads this from its session.
SIGNED_IN_USER = {
    "id": "customer-1001",
    "email": "ada.lovelace@example.com",
    "first_name": "Ada",
    "last_name": "Lovelace",
}

# What we know about each user's link, by user id. A real app uses its database.
links = {}

# A connection id goes into a URL path, so check its shape before you use it.
CONNECTION_ID = re.compile(r"[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}")


def page(text, status=200):
    return f"<p>{text}</p>", status


def explain(error):
    if error.code == "external_id_conflict":
        return page("Your email changed. Contact support so we can fix the link.", 409)
    if error.code == "person_already_connected":
        return page("This email is already linked to another account. Sign in to that account.", 409)
    print(error)
    return page("We could not start the link. Try again later.", 502)


@app.get("/nurishd/connect")
def connect():
    user = SIGNED_IN_USER
    try:
        customer = call(
            "POST",
            "/meals/v1/customer/create/document",
            body={
                "external_id": user["id"],
                "email": user["email"],
                "first_name": user["first_name"],
                "last_name": user["last_name"],
                "return_url": RETURN_URL,
            },
        )
    except NurishdError as error:
        return explain(error)
    connection = customer["connection"]
    links[user["id"]] = {
        "customer_id": customer["user"],
        "connection_id": connection["connection_id"],
        "connected": connection["status"] == "active",
    }
    if customer["connect_url"] is None:
        return redirect("/me")
    return redirect(customer["connect_url"])


@app.get("/nurishd/return")
def come_back():
    user = SIGNED_IN_USER
    connection_id = request.args.get("connection_id", "")
    if not CONNECTION_ID.fullmatch(connection_id):
        return page("This link is not valid.", 400)
    try:
        connection = call("GET", f"/meals/v1/connection/{connection_id}/get/document")
    except NurishdError as error:
        if error.status == 404:
            return page("We do not know this connection.", 404)
        print(error)
        return page("We could not check the connection.", 502)
    if connection["external_id"] != user["id"]:
        return page("This connection belongs to someone else.", 403)
    if connection["status"] == "active":
        links[user["id"]] = {
            "customer_id": connection["user"],
            "connection_id": connection["connection_id"],
            "connected": True,
        }
        return page("You are connected to Nurish'd.")
    if connection["status"] == "pending":
        return page("Not approved yet. Go to /nurishd/connect for a new link.")
    if connection["status"] == "declined":
        return page("You declined the link. Go to /nurishd/connect to start again.")
    return page("The link ended. Go to /nurishd/connect to start again.")


@app.get("/me")
def me():
    user = SIGNED_IN_USER
    if links.get(user["id"], {}).get("connected"):
        return page(f"{user['first_name']}, you are connected to Nurish'd.")
    return page(f"{user['first_name']}, you are not connected yet. Go to /nurishd/connect.")


app.run(port=3000)
```

```javascript
// file: connect.js
import express from 'express';

import { NurishdError, call } from './nurishd.js';

const app = express();

// The return URL you registered in the console. It starts with https://.
const RETURN_URL = process.env.NURISHD_RETURN_URL ?? '';
if (!RETURN_URL) throw new Error('Set NURISHD_RETURN_URL first.');

// Stands in for your own sign-in. A real app reads this from its session.
const signedInUser = {
	id: 'customer-1001',
	email: 'ada.lovelace@example.com',
	firstName: 'Ada',
	lastName: 'Lovelace',
};

// What we know about each user's link, by user id. A real app uses its database.
const links = new Map();

// A connection id goes into a URL path, so check its shape before you use it.
const CONNECTION_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/;

function page(res, text, status = 200) {
	res.status(status).send(`<p>${text}</p>`);
}

function explain(res, error) {
	if (error.code === 'external_id_conflict') {
		return page(
			res,
			'Your email changed. Contact support so we can fix the link.',
			409,
		);
	}
	if (error.code === 'person_already_connected') {
		return page(
			res,
			'This email is already linked to another account. Sign in to that account.',
			409,
		);
	}
	console.log(error.message);
	return page(res, 'We could not start the link. Try again later.', 502);
}

app.get('/nurishd/connect', async (req, res) => {
	const user = signedInUser;
	let customer;
	try {
		customer = await call('POST', '/meals/v1/customer/create/document', {
			body: {
				external_id: user.id,
				email: user.email,
				first_name: user.firstName,
				last_name: user.lastName,
				return_url: RETURN_URL,
			},
		});
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		return explain(res, error);
	}
	links.set(user.id, {
		customerId: customer.user,
		connectionId: customer.connection.connection_id,
		connected: customer.connection.status === 'active',
	});
	if (customer.connect_url === null) return res.redirect('/me');
	res.redirect(customer.connect_url);
});

app.get('/nurishd/return', async (req, res) => {
	const user = signedInUser;
	const connectionId = String(req.query.connection_id ?? '');
	if (!CONNECTION_ID.test(connectionId)) {
		return page(res, 'This link is not valid.', 400);
	}
	let connection;
	try {
		connection = await call(
			'GET',
			`/meals/v1/connection/${connectionId}/get/document`,
		);
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		if (error.status === 404) {
			return page(res, 'We do not know this connection.', 404);
		}
		console.log(error.message);
		return page(res, 'We could not check the connection.', 502);
	}
	if (connection.external_id !== user.id) {
		return page(res, 'This connection belongs to someone else.', 403);
	}
	if (connection.status === 'active') {
		links.set(user.id, {
			customerId: connection.user,
			connectionId: connection.connection_id,
			connected: true,
		});
		return page(res, "You are connected to Nurish'd.");
	}
	if (connection.status === 'pending') {
		return page(
			res,
			'Not approved yet. Go to /nurishd/connect for a new link.',
		);
	}
	if (connection.status === 'declined') {
		return page(
			res,
			'You declined the link. Go to /nurishd/connect to start again.',
		);
	}
	page(res, 'The link ended. Go to /nurishd/connect to start again.');
});

app.get('/me', (req, res) => {
	const user = signedInUser;
	if (links.get(user.id)?.connected) {
		return page(res, `${user.firstName}, you are connected to Nurish'd.`);
	}
	page(
		res,
		`${user.firstName}, you are not connected yet. Go to /nurishd/connect.`,
	);
});

app.listen(3000, () => console.log('Listening on http://localhost:3000'));
```

```typescript
// file: connect.ts
import express, { type Response } from 'express';

import { NurishdError, call } from './nurishd.ts';

interface Connection {
	connection_id: string;
	user: string;
	external_id: string;
	status: 'pending' | 'active' | 'declined' | 'revoked';
}

interface Customer {
	user: string;
	connection: Connection;
	connect_url: string | null;
}

interface Link {
	customerId: string;
	connectionId: string;
	connected: boolean;
}

const app = express();

// The return URL you registered in the console. It starts with https://.
const RETURN_URL = process.env.NURISHD_RETURN_URL ?? '';
if (!RETURN_URL) throw new Error('Set NURISHD_RETURN_URL first.');

// Stands in for your own sign-in. A real app reads this from its session.
const signedInUser = {
	id: 'customer-1001',
	email: 'ada.lovelace@example.com',
	firstName: 'Ada',
	lastName: 'Lovelace',
};

// What we know about each user's link, by user id. A real app uses its database.
const links = new Map<string, Link>();

// A connection id goes into a URL path, so check its shape before you use it.
const CONNECTION_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/;

function page(res: Response, text: string, status = 200) {
	res.status(status).send(`<p>${text}</p>`);
}

function explain(res: Response, error: NurishdError) {
	if (error.code === 'external_id_conflict') {
		return page(
			res,
			'Your email changed. Contact support so we can fix the link.',
			409,
		);
	}
	if (error.code === 'person_already_connected') {
		return page(
			res,
			'This email is already linked to another account. Sign in to that account.',
			409,
		);
	}
	console.log(error.message);
	return page(res, 'We could not start the link. Try again later.', 502);
}

app.get('/nurishd/connect', async (req, res) => {
	const user = signedInUser;
	let customer: Customer;
	try {
		customer = await call<Customer>(
			'POST',
			'/meals/v1/customer/create/document',
			{
				body: {
					external_id: user.id,
					email: user.email,
					first_name: user.firstName,
					last_name: user.lastName,
					return_url: RETURN_URL,
				},
			},
		);
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		return explain(res, error);
	}
	links.set(user.id, {
		customerId: customer.user,
		connectionId: customer.connection.connection_id,
		connected: customer.connection.status === 'active',
	});
	if (customer.connect_url === null) return res.redirect('/me');
	res.redirect(customer.connect_url);
});

app.get('/nurishd/return', async (req, res) => {
	const user = signedInUser;
	const connectionId = String(req.query.connection_id ?? '');
	if (!CONNECTION_ID.test(connectionId)) {
		return page(res, 'This link is not valid.', 400);
	}
	let connection: Connection;
	try {
		connection = await call<Connection>(
			'GET',
			`/meals/v1/connection/${connectionId}/get/document`,
		);
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		if (error.status === 404) {
			return page(res, 'We do not know this connection.', 404);
		}
		console.log(error.message);
		return page(res, 'We could not check the connection.', 502);
	}
	if (connection.external_id !== user.id) {
		return page(res, 'This connection belongs to someone else.', 403);
	}
	if (connection.status === 'active') {
		links.set(user.id, {
			customerId: connection.user,
			connectionId: connection.connection_id,
			connected: true,
		});
		return page(res, "You are connected to Nurish'd.");
	}
	if (connection.status === 'pending') {
		return page(
			res,
			'Not approved yet. Go to /nurishd/connect for a new link.',
		);
	}
	if (connection.status === 'declined') {
		return page(
			res,
			'You declined the link. Go to /nurishd/connect to start again.',
		);
	}
	page(res, 'The link ended. Go to /nurishd/connect to start again.');
});

app.get('/me', (req, res) => {
	const user = signedInUser;
	if (links.get(user.id)?.connected) {
		return page(res, `${user.firstName}, you are connected to Nurish'd.`);
	}
	page(
		res,
		`${user.firstName}, you are not connected yet. Go to /nurishd/connect.`,
	);
});

app.listen(3000, () => console.log('Listening on http://localhost:3000'));
```

```java
// file: src/main/java/tutorial/Connect.java
package tutorial;

import com.fasterxml.jackson.databind.JsonNode;
import io.javalin.Javalin;
import io.javalin.http.Context;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import tutorial.Nurishd.NurishdException;

public class Connect {
    // The return URL you registered in the console. It starts with https://.
    static final String RETURN_URL = System.getenv("NURISHD_RETURN_URL");

    // Stands in for your own sign-in. A real app reads this from its session.
    static final String USER_ID = "customer-1001";
    static final String EMAIL = "ada.lovelace@example.com";
    static final String FIRST_NAME = "Ada";
    static final String LAST_NAME = "Lovelace";

    // What we know about a user's link.
    record Link(String customerId, String connectionId, boolean connected) {}

    // The links by user id. A real app uses its database.
    static final Map<String, Link> links = new HashMap<>();

    // A connection id goes into a URL path, so check its shape before you use it.
    static final Pattern CONNECTION_ID = Pattern.compile("[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}");

    static void page(Context ctx, String text, int status) {
        ctx.status(status).html("<p>" + text + "</p>");
    }

    static void explain(Context ctx, NurishdException error) {
        if (error.code.equals("external_id_conflict")) {
            page(ctx, "Your email changed. Contact support so we can fix the link.", 409);
        } else if (error.code.equals("person_already_connected")) {
            page(ctx, "This email is already linked to another account. Sign in to that account.", 409);
        } else {
            System.out.println(error.getMessage());
            page(ctx, "We could not start the link. Try again later.", 502);
        }
    }

    static void connect(Context ctx) {
        JsonNode customer;
        try {
            customer = Nurishd.call(
                    "POST",
                    "/meals/v1/customer/create/document",
                    Map.of(),
                    Map.of(
                            "external_id", USER_ID,
                            "email", EMAIL,
                            "first_name", FIRST_NAME,
                            "last_name", LAST_NAME,
                            "return_url", RETURN_URL));
        } catch (NurishdException error) {
            explain(ctx, error);
            return;
        }
        JsonNode connection = customer.path("connection");
        links.put(USER_ID, new Link(
                customer.path("user").asText(),
                connection.path("connection_id").asText(),
                connection.path("status").asText().equals("active")));
        if (customer.path("connect_url").isNull()) {
            ctx.redirect("/me");
        } else {
            ctx.redirect(customer.path("connect_url").asText());
        }
    }

    static void comeBack(Context ctx) {
        String connectionId = ctx.queryParamAsClass("connection_id", String.class).getOrDefault("");
        if (!CONNECTION_ID.matcher(connectionId).matches()) {
            page(ctx, "This link is not valid.", 400);
            return;
        }
        JsonNode connection;
        try {
            connection = Nurishd.call("GET", "/meals/v1/connection/%s/get/document".formatted(connectionId));
        } catch (NurishdException error) {
            if (error.status == 404) {
                page(ctx, "We do not know this connection.", 404);
                return;
            }
            System.out.println(error.getMessage());
            page(ctx, "We could not check the connection.", 502);
            return;
        }
        if (!connection.path("external_id").asText().equals(USER_ID)) {
            page(ctx, "This connection belongs to someone else.", 403);
            return;
        }
        String status = connection.path("status").asText();
        if (status.equals("active")) {
            links.put(USER_ID, new Link(
                    connection.path("user").asText(),
                    connection.path("connection_id").asText(),
                    true));
            page(ctx, "You are connected to Nurish'd.", 200);
        } else if (status.equals("pending")) {
            page(ctx, "Not approved yet. Go to /nurishd/connect for a new link.", 200);
        } else if (status.equals("declined")) {
            page(ctx, "You declined the link. Go to /nurishd/connect to start again.", 200);
        } else {
            page(ctx, "The link ended. Go to /nurishd/connect to start again.", 200);
        }
    }

    static void me(Context ctx) {
        Link link = links.get(USER_ID);
        if (link != null && link.connected()) {
            page(ctx, FIRST_NAME + ", you are connected to Nurish'd.", 200);
        } else {
            page(ctx, FIRST_NAME + ", you are not connected yet. Go to /nurishd/connect.", 200);
        }
    }

    public static void main(String[] args) {
        if (RETURN_URL == null || RETURN_URL.isBlank()) {
            System.out.println("Set NURISHD_RETURN_URL first.");
            System.exit(1);
        }
        Javalin app = Javalin.create();
        app.get("/nurishd/connect", Connect::connect);
        app.get("/nurishd/return", Connect::comeBack);
        app.get("/me", Connect::me);
        app.start(3000);
    }
}
```

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- file: pom.xml -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>nurishd-tutorial</artifactId>
  <version>1.0.0</version>

  <properties>
    <maven.compiler.release>17</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.17.2</version>
    </dependency>
    <dependency>
      <groupId>io.javalin</groupId>
      <artifactId>javalin</artifactId>
      <version>6.3.0</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>2.0.16</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>3.4.1</version>
      </plugin>
    </plugins>
  </build>
</project>
```

## If something goes wrong

| What you see                                          | Why                                                                   | What to do                                                                                                  |
| ----------------------------------------------------- | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `409 external_id_conflict` on create                  | The `external_id` belongs to a customer with another email.           | Keep using the first id of the person. Do not change it.                                                    |
| `409 person_already_connected` on create              | The email is connected under another `external_id`.                   | Use the id you first gave to this person.                                                                   |
| `422 validation_error` on create                      | A field is wrong, or the return URL is not `https` or not registered. | Register the return URL in the console. Use the tunnel address, not `http` or `localhost`. Check the email. |
| `Set NURISHD_RETURN_URL first.`                       | The variable is not set in this terminal.                             | Run the `export` or `$env` command from step 1 again in the same terminal.                                  |
| `403 scope_not_granted`                               | Your key lacks `order:write` or `order:read`.                         | Create a key with both scopes.                                                                              |
| `404 not_found` when you read the connection          | The id does not exist, or it belongs to another environment.          | Use the `connection.connection_id` of the create answer in the same Sandbox.                                |
| The Nurish'd page does not open or says the link used | The link works once and for 24 hours, or it was in a frame.           | Open `/nurishd/connect` again for a fresh link. Open it as a full page.                                     |

## Next

- [Customers](/docs/meals/customers): every customer route.
- [Connections](/docs/concepts/connections): statuses, scopes and return URLs.
- [Show meals for an address and a date](/docs/tutorials/show-meals-for-an-address): find what to order.
- [Place a meal order](/docs/tutorials/place-a-meal-order): order for a connected customer.
