Express specify default behavior for route

Viewed 22

I am creating an app with express, next and ace (atlassian-connect-express).

Express + next requires me to use routes like this:

app.all('*', (req, res) => {
  return handle(req, res)
})

But I need special behavior for an atlassian-connect.json. In the ace example, it is done like this:

app.get('/', (_, res) => {
  res.redirect('/atlassian-connect.json');
})

The problem with that is that the first route will still be used for /atlassian-connect.json, so I have to overwrite that as well.

But if I try it manually like this, I run into the following problem:

app.get('/atlassian-connect.json', (_, res) => {
  let content = fs.readFileSync(path.resolve('atlassian-connect.json'));
  let json = JSON.parse(content);
  res.send(json)
})

The json contains a part like this:

"baseUrl": "{{localBaseUrl}}"

And the localBaseUrl gets automatically filled out if I dont have a manual route for /atlassian-connect.json. When I do use my route, it doesn't fill it out. How can I fill it out?

1 Answers

What I found out that this sending the filled out json is not something default from express but rather something the ace module does.

So the way I found is to just define all the routes manually like this:

app.get('/', (_, res) => {
  res.redirect('/atlassian-connect.json');
})

// all routes to be accessible

app.all('/app', (req, res) => {
  return handle(req, res)
})

// all compiled next route
app.all('/_next/*', (req, res) => {
  return handle(req, res)
})

I tried using regex to match on all the routes except the atlassian-connect.json and came up with this: ^(?!atlassian-connect.json$).*$ but it doesn't seem to work.. So I guess the easiest way is just to declare all the routes manually.

EDIT:

I figured out how to get the regex to work (silly me not reading the docs)

Fixed routing:

// ace configuration
app.get('/', (_, res) => {
  res.redirect('/atlassian-connect.json');
})

// all routes except /atlassian-connect.json
app.all(/^(?!\/atlassian-connect.json$).*$/, (req, res) => {
  return handle(req, res)
})
Related