# Running Next.JS and React /inside/ of ActionHero
This server will render dynamic next.js/react pages on some routes, and normal ActionHero API requests on others.
This configuration works with both Next and ActionHero hot reloading of code.
A more detailed example showcasing how to use fetch and web sockets to interact with your API can be found here: https://github.com/actionhero/next-in-actionhero
## To install:
(assuming you have [node](http://nodejs.org/) and NPM installed)
`npm install`
## To Run:
`npm start`
## How does this work?
1. Create an initializer to load next.js and create a handler that can extract the normal node `req` and `res` from the connection
if(connection.type!=='web'){thrownewError('Connections for NEXT apps must be of type "web"')}
constreq=connection.rawConnection.req
constres=connection.rawConnection.res
returnapi.next.handle(req,res)
}
}
api.next.dev=(api.env==='development')
if(api.next.dev){api.log('Running next in development mode...')}
api.next.app=next({dev:api.next.dev})
api.next.handle=api.next.app.getRequestHandler()
awaitapi.next.app.prepare()
}
asyncstop(){
awaitapi.next.app.close()
}
}
```
2. Create an action which will run the above `api.next.render(connection)`. Note that we will not be relying on ActionHero to respond to the client's request in this case, and leave that up to next (via: `data.toRender = false`)
```js
// actions/next.js
const{Action,api}=require('actionhero')
module.exports=classCreateChatRoomextendsAction{
constructor(){
super()
this.name='render'
this.description='I render the next.js react website'
}
asyncrun(data){
data.toRender=false
returnapi.next.render(data.connection)
}
}
```
3. Tell ActionHero to use the api rather than the file server as the top-level route in `api.config.servers.web.rootEndpointType = 'api'`. This will allows "/" to listen to API requests. Also update `api.config.general.paths.public = [ path.join(__dirname, '/../static') ]`. In this configuration, the next 'static' renderer will take priority over the ActionHero 'public file' api. Note that any static assets (CSS, fonts, etc) will need to be in "./static" rather than "./public".
Note that this is where the websocket server, if you enable it, will place the `ActionheroWebsocketClient` libraray.
4. Configure a wild-card route at the lowest priority of your GET handler to catch all web requests that aren't caught by other actions:
// Which IP to listen on (use '0.0.0.0' for all; '::' for all on ipv4 and ipv6)
// Set to `null` when listening to socket
bindIP:'0.0.0.0',
// Any additional headers you want actionhero to respond with
httpHeaders:{
'X-Powered-By':api.config.general.serverName,
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS, TRACE',
'Access-Control-Allow-Headers':'Content-Type'
},
// Route that actions will be served from; secondary route against this route will be treated as actions,
// IE: /api/?action=test == /api/test/
urlPathForActions:'api',
// Route that static files will be served from;
// path (relative to your project root) to serve static content from
// set to `null` to disable the file server entirely
urlPathForFiles:'public',
// When visiting the root URL, should visitors see 'api' or 'file'?
// Visitors can always visit /api and /public as normal
rootEndpointType:'api',
// simple routing also adds an 'all' route which matches /api/:action for all actions
simpleRouting:true,
// queryRouting allows an action to be defined via a URL param, ie: /api?action=:action
queryRouting:true,
// The cache or (if etags are enabled) next-revalidation time to be returned for all flat files served from /public; defined in seconds
flatFileCacheDuration:60,
// Add an etag header to requested flat files which acts as fingerprint that changes when the file is updated;
// Client will revalidate the fingerprint at latest after flatFileCacheDuration and reload it if the etag (and therfore the file) changed
// or continue to use the cached file if it's still valid
enableEtag:true,
// should we save the un-parsed HTTP POST/PUT payload to connection.rawConnection.params.rawBody?
saveRawBody:false,
// How many times should we try to boot the server?
// This might happen if the port is in use by another process or the socketfile is claimed
bootAttempts:1,
// Settings for determining the id of an http(s) request (browser-fingerprint)
fingerprintOptions:{
cookieKey:'sessionID',
toSetCookie:true,
onlyStaticElements:false,
settings:{
path:'/',
expires:3600000
}
},
// Options to be applied to incoming file uploads.
// More options and details at https://github.com/felixge/node-formidable
formOptions:{
uploadDir:os.tmpdir(),
keepExtensions:false,
maxFieldsSize:1024*1024*100
},
// Should we pad JSON responses with whitespace to make them more human-readable?
// set to null to disable
padding:2,
// Options to configure metadata in responses
metadataOptions:{
serverInformation:true,
requesterInformation:true
},
// When true, returnErrorCodes will modify the response header for http(s) clients if connection.error is not null.
// You can also set connection.rawConnection.responseHttpCode to specify a code per request.
returnErrorCodes:true,
// should this node server attempt to gzip responses if the client can accept them?
// this will slow down the performance of actionhero, and if you need this funcionality, it is recommended that you do this upstream with nginx or your load balancer
compress:false,
// options to pass to the query parser
// learn more about the options @ https://github.com/hapijs/qs