1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

Add root static files example (#1835)

This commit is contained in:
Brendan Houle 2017-04-30 10:30:29 -04:00 committed by Tim Neutkens
parent 25dbcce60b
commit 03bfaecf49
7 changed files with 86 additions and 0 deletions

View file

@ -0,0 +1,29 @@
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/custom-server)
# Root static files example
## How to use
Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/custom-server
cd custom-server
```
Install it and run:
```bash
npm install
npm run dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
This example demonstrates how to serve files such as /robots.txt and /sitemap.xml from the root.

View file

@ -0,0 +1,12 @@
{
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
},
"dependencies": {
"next": "latest",
"react": "^15.5.4",
"react-dom": "^15.5.4"
}
}

View file

@ -0,0 +1,7 @@
export default () => (
<ul>
<li><a href='/robots.txt'>/robots.txt</a></li>
<li><a href='/sitemap.xml'>/sitemap.xml</a></li>
<li><a href='/favicon.ico'>/favicon.ico</a></li>
</ul>
)

View file

@ -0,0 +1,30 @@
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const { join } = require('path')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true)
const rootStaticFiles = [
'/robots.txt',
'/sitemap.xml',
'/favicon.ico'
]
if (rootStaticFiles.indexOf(parsedUrl.pathname) > -1) {
const path = join(__dirname, 'static', parsedUrl.pathname)
app.serveStatic(req, res, path)
} else {
handle(req, res, parsedUrl)
}
})
.listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View file

@ -0,0 +1,2 @@
User-agent: *
Disallow: /

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/foo.html</loc>
</url>
</urlset>