The common practice in web development is always separate the client and server side into two applications. However, sometimes we are going to create a simple application which consists of only 1 or 2 features or it's for testing purpose. In this case, what we can do is combining both client and server into 1 application using Next.js.
The following steps show the setup of client and server with Next.js.
Client Setup
- Create a new Next.js app
npx create-next-app
# or
yarn create next-app
- Install packages
npm install next react react-dom body-parser express next-routes
# or
yarn add next react react-dom body-parser express next-routes
- Update
/pages/index.js
which is the root page (localhost:3000) with the codes below.
import React from "react";
function HomePage() {
return <h3>{'Welcome '}</h3>
}
- Try running the app with command npm run dev, navigate to localhost:3000 and you should be able to see Welcome in the page.
Server Setup
- Create a folder for server setup. Create a GET endpoint in
/server/api/get/index.js
const express = require('express');
const router = express.Router();
router.get('/name', (req, res) => {
res.status(200).json({name: 'Panda'});
});
module.exports = router
- Update
/pages/index.js
to get response from the GET endpoint and pass into the function as props.
function HomePage({name}) {
return <h3>{'Welcome ' + name}</h3>
}
export async function getStaticProps() {
const res = await fetch('http://localhost:3000/name')
const result = await res.json()
return {
props: {
name: result.name,
},
}
}
Client + Server Rendering
- Create
app.js
in server folder
const express = require('express');
const next = require('next');
const bodyParser = require('body-parser');
const routes = require('../routes');
const getRoute = require("./api/get");
const dev = true;
const app = next({ dev });
const handle = app.getRequestHandler();
const handler = routes.getRequestHandler(app);
app.prepare()
.then(async () => {
//declare Express Engine
const server = express();
server.use(bodyParser.json());
// backend routes
server.use(getRoute);
// frontend routes
server.use(handler)
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, (err) => {
if (err) throw err
console.log('> Ready on port 3000')
})
})
- Update
package.json
to run app.js
"scripts": {
"start-server": "node ./server/app.js",
"dev": "next dev",
"build": "next build",
"start": "next start"
}
- Try running the application with command npm run start-server. You should be able to see Welcome Panda in the page.
That's all for my sharing regarding the quickstart for Next.js SSR with API! Feel free to comment if any idea :)
Reference: Next.js Docs | Full Code