To get started with starting a server in Koa, we should first create a project directory and enter that directory. We can do so with the following commands:
mkdir koa-server
cd koa-server
Next, we initialize a project in npm with the following command:
npm init
After running this command, follow the prompts to help create a package.json file for your project.
Next, we can install Koa to our project with the following command:
npm i koa
Now that we have Koa installed, we can create our server file. Let's call the file index.js. If you are using a Unix-based operating system such as Linux or macOS, you can create the file with the following command:
touch index.js
This file will serve as the entry point to our application, and we will write the main logic for our simple server in this file. Using your code or text editor of choice, write the following into the index.js file:
// ./index.js
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(1234, () => {
console.log('Server is running on port 1234')
});
In the preceding code snippet, first, we require the needed Koa application class and assign it to the Koa variable. Next, we initialize a new Koa application instance with new Koa() and assign it to app. One interesting thing we see next is the definition of a simple middleware.
The middleware we define simply sends back the text Hello World as a response to every request. We define the middleware using the .use() method available in Koa. The .use() method accepts the middleware function as its only argument. The middleware function also takes the context object (defined as ctx) as its only argument, which it uses to process requests and send responses. It specifically uses the context.body method to send the Hello World response. If you feel a little lost at this point, don't worry. We will discuss more Koa core concepts and the context object in Chapter 3, Koa Core Concepts.
Finally, we start the server with the app.listen() function, which takes the port to run the server as its first argument. In our case, we defined 1234 as the port to run our server on. The second argument is a callback function, which is called once the server starts.
We can now start the app with the following command:
node index.js
This starts our server, and if we visit http://localhost:1234, we will see the Hello World response. We can also test this in the Terminal using the curl command:
curl -i http://localhost:1234
It should send back a response similar to this:
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 11
Connection: keep-alive
Hello World