# Express File Serving Tips

#### You:
this works?
app.get(['showcase1.mp4', '/showcase1'], (req, res) => {
    const p = path.join(__dirname, 'showcase1.mp4');
    if (fs.existsSync(p)) {
        res.setHeader('Content-Type', 'video/mp4');
        res.setHeader('Cache-Control', 'public, max-age=3600');
        return res.sendFile(p);
    }
    return res.status(404).type('text/plain').send('showcase1.mp4 not found on server');
});

#### ChatGPT:
Yes-**this will work in Express**, but there are a few important nuances and small improvements you should consider.

### ✅ What your code does correctly

- `app.get(['showcase1.mp4', '/showcase1'], ...)`\
  ✔ Express supports an array of routes, so both URLs will match:
  - `/showcase1.mp4`
  - `/showcase1`

- `fs.existsSync(p)`\
  ✔ Checks that the file exists before trying to serve it.

- `res.sendFile(p)`\
  ✔ Correct way to serve a file in Express.

- Setting `Content-Type: video/mp4`\
  ✔ Correct for MP4 video.

---

### ⚠️ Issues / improvements

#### 1. `sendFile` already sets headers (you may be duplicating work)

`res.sendFile()` automatically sets:

- `Content-Type` (based on extension)
- `Content-Length`
- proper streaming behavior

So this line is optional:

```js
res.setHeader('Content-Type', 'video/mp4');
```

Not harmful, but unnecessary.

---

#### 2. You are missing error handling for `sendFile`

If something goes wrong (permissions, etc.), Express won’t explicitly handle it unless you pass a callback.

Better:

```js
return res.sendFile(p, (err) => {
    if (err) {
        res.status(500).send('Error sending file');
    }
});
```

---

#### 3. `existsSync` is not needed (and can be unsafe at scale)

This is a common Express anti-pattern:

```js
if (fs.existsSync(p))
```

Why:

- It adds an extra filesystem call
- It introduces a race condition (file could disappear between check and send)

👉 Better to just call `sendFile` and handle errors.

---

#### 4. Route design note

This is a bit unusual:

```js
['showcase1.mp4', '/showcase1']
```

Usually you’d do:

- `/showcase1` → cleaner public URL
- OR serve static files via `express.static`

Example better approach:

```js
app.use(express.static(path.join(__dirname, 'public')));
```

Then just put:

```
public/showcase1.mp4
```

---

### ✅ Cleaner version of your code

```js
app.get(['/showcase1.mp4', '/showcase1'], (req, res) => {
    const p = path.join(__dirname, 'showcase1.mp4');

    return res.sendFile(p, (err) => {
        if (err) {
            res.status(404).type('text/plain').send('showcase1.mp4 not found on server');
        }
    });
});
```

---

### 🚀 Best practice (recommended)

If this is just a static video:

```js
app.use(express.static(__dirname));
```

Then:

- `/showcase1.mp4` works automatically
- no custom route needed

---

If you want, I can also show you how to:

- stream large videos properly (range requests)
- add download vs inline playback headers
- or protect the file behind authentication
