Chopin
FrameworksExpress

Express

This guide is a work in progress. While it is generally accurate, it has not been fully tested.

Chopin works with any web framework, including Express.js.

Starting a new project

Start by creating a new Express.js project.

npx express-generator

Next, cd into the project and install the dependencies.

cd myapp
npm install

After installing the dependencies, you can start the server. Which will be available at http://localhost:3000.

npm start

However, this is not how we will run it once it is integrated with Chopin Framework. Continue reading to learn how to integrate it.

Integrating with an existing project

First, initialized the integration with chopd.

npx chopd init

Next, update the command field in the chopd.config.ts file to say npm start:

{
    "command": "npm start",
    "proxyPort": 4000,
    "targetPort": 3000
}

Finally, you can run your app with the following command:

npx chopd

And you will be able to access your app at http://localhost:4000. Do not use npm start to run your app or and do not access it through port 3000.

Handling authentication

Working with authentication in Express is similar to Next.js. However, right now we do not have an official Express package for Chopin. Nevertheless, here is an example for how you can access the logged in user in an Express route.

app.get('/me', (req, res) => {
    const address = req.headers['x-address'];
    if (!address) {
        return res.status(401).json({ error: 'Not authenticated' });
    }
    res.json({ address });
});

For full details, read the authentication documentation.

Fetching random numbers and timestamps

Non-deterministic functions (e.g. fetch, crypto.randomBytes, Date.now()) executed on the server must be called using the oracle module. However, there is no official Express package for this either. Therefore, you will need integrate it with @chopinframework/core yourself.

First, install the core package.

npm install @chopinframework/core

Then you need to instantiate the Oracle class by using the value of the x-callback-url header.

import { Oracle } from '@chopinframework/core';
 
app.get('/now', async (req, res) => {
    const oracle = new Oracle(req.headers['x-callback-url']);
    const timestamp = await oracle.now();
    res.json({ timestamp });
});

For full details, read the oracle documentation.

User interface

To build a UI in your Express app, no additional changes are needed. To handle authentication on the client side, read the authentication documentation.