salesforce/lwc

KOA Server Not Able to Add Routes

Opened this issue · 2 comments

Issue

When using the LWR server and exposing the Express internal server, that will work fine. LWR documentation also says it supports KOA server which I would like to attempt to use. However, when I implement my server and try to utilize 'koa', I am able to set a response header, but I cannot seem to get any routes which are injected to function properly. I was wondering if 'koa' functions properly and/or if anyone has been able to get this to work. I am not sure this is the right repository so thanks for redirecting me if I am in the wrong location.

Steps to Reproduce

  • lwr.config
{
    "port": 3000,
    "serverMode": "dev",
    "serverType": "koa",   
}
  • server.js
import { createServer } from "lwr";
import Router from 'koa-router';

const lwrServer = createServer();

// create app instance (i.e. get the internal 'koa' server)
const koaApp = lwrServer.getInternalServer("koa");

// middleware functions
const koaRouter = new Router();
koaRouter.get('/greetings', async (ctx, next) => {
    ctx.body = "Hello, World!";
    await next();
});

koaApp.use(async (ctx, next) => {
    ctx.response.set('koa-custom-header', 'Koa middleware is running!');
    await next();
}).use(koaRouter.routes());

lwrServer.listen(({ port, serverMode}) => {
    console.log(`Server started on http://localhost:${port} in ${serverMode} mode`);
}).catch((err) => {
    console.error(err);
    process.exit(1);
});

Expected Results

I expected the /greetings URL to return with 'Hello, world!'

Actual Results

404: Could not find view at "/greetings"

Notes

If I wire up the koaApp directly as I have done above and use "listen" on the koaApp rather than issuing listen on the lwrServer, then the routes will resolve fine. Of course, none of the LWR Server itself will function any longer. This makes me wonder if "koa" is truly supported in the same way 'express' is... but again, I could just be missing something.

@jeffolmstead can you detail your use case for using KOA over Express?

LWR handles Express/KOA routing internally, so adding your own external router is not an expected pattern and is unlikely to work (or be supported).

You can still add middleware that handles custom routes via:

// Express custom middleware example
const expressApp = lwrServer.getInternalServer<'express'>();
expressApp.use(async (req, res, next) => {
    const { path: requestPath } = req;
      if (requestPath === '/greetings') {
         // do something 
      } else {
         return next();
      }
});
// KOA custom middleware example
const koaApp = lwrServer.getInternalServer<'koa'>();

// Add koa middleware directly
koaApp.use(async (ctx, next) => {
      if (ctx.path === '/greetings') {
         // do something 
      } else {
         return next();
      }
});

@khangiskhan thanks for your reply and examples. As a background, I am working through trying to push the limits of LWR (while also trying to work within the approach it was designed for) prior to pushing into a specific use case for it. Using KOA over Express was purely to gain an understanding of the options presented by the LWR stack of exposing the internal server implementations.

Overarching Goals
The overarching goal of having the routes was to be able to test out the serving of REST API endpoints (or even GraphQL). I was able to do this with the "Express" server exposed, but the "KOA" didn't seem to be able to inject a new route. I will try your example above.

I also realize I might need to switch my mentality down to the Web Component level with each maintaining it's own data access as opposed to a whole page mentality. In order to build working prototypes on LWR, I am trying to get the basics understood:

  • Authentication
  • Efficient data serving
  • Potential for API access

Basically boilerplate stuff to have a business solution, but how does it fit into LWR. Here is what I have encountered with authentication:

There are a lot of good examples for serving up LWR on node.js without authentication, and I have tapped into them. However, when trying to test out possibilities for having authenticated users (easy to do on Salesforce Experience sites), finding a working solution in an LWR server environment hasn't been easy. This is what led me to attempting to tap directly into the internal Express server.

TLDR
I am trying to figure out the extension points / best approach for integrating authentication and, if need be, API endpoints.

I will try out your example above and provide feedback after testing. If you have time to provide additional response, it is appreciated.