title: Quick Start

This guide covers getting up and running a real example using Egg.
By following along with this guide step by step, you can quickly get started with Egg development.

Prerequisites

  • Operating System: Linux, OS X or Windows.
  • Node.js Runtime: 8.x or newer; it is recommended that you use LTS Releases.

the Quick Way

To begin with, let’s quickly initialize the project by using a scaffold,
which will quickly generate some of the major pieces of the application.

  1. $ npm i egg-init -g
  2. $ egg-init egg-example --type=simple
  3. $ cd egg-example
  4. $ npm i

Then get up and run by using the following commands.

  1. $ npm run dev
  2. $ open localhost:7001

Step by Step

Usually you can just use egg-init of the previous section,
choose a scaffold that best fits your business model and quickly generate a project,
then get started with the development.

However, in this section, instead of using scaffolds we will build a project called Egg HackerNews step by step, for a better understanding of how it works.

Egg HackerNews Snapshoot

Initialization

First let’s create the project directory and initialize its structure.

  1. $ mkdir egg-example
  2. $ cd egg-example
  3. $ npm init
  4. $ npm i egg --save
  5. $ npm i egg-bin --save-dev

Then add npm scripts to package.json.

  1. {
  2. "name": "egg-example",
  3. "scripts": {
  4. "dev": "egg-bin dev"
  5. }
  6. }

Create a Controller

If you are familiar with the MVC architecture,
you might have already guessed that the first thing to create
is a controller and router.

  1. // app/controller/home.js
  2. const Controller = require('egg').Controller;
  3. class HomeController extends Controller {
  4. async index() {
  5. this.ctx.body = 'Hello world';
  6. }
  7. }
  8. module.exports = HomeController;

Then edit the router file and add a mapping.

  1. // app/router.js
  2. module.exports = app => {
  3. const { router, controller } = app;
  4. router.get('/', controller.home.index);
  5. };

Then add a configuration file:

  1. // config/config.default.js
  2. exports.keys = <YOUR_SECURITY_COOKE_KEYS>;

The project directory looks like this:

  1. egg-example
  2. ├── app
  3. ├── controller
  4. └── home.js
  5. └── router.js
  6. ├── config
  7. └── config.default.js
  8. └── package.json

For more information about directory structure, see Directory Structure.

Now you can start up the Web Server and see your application in action.

  1. $ npm run dev
  2. $ open localhost:7001

Note:

  • You could write Controller with class or exports style, see more detail at Controller.
  • And Config could write with module.exports or exports style, see more detail at Node.js modules docs.

Add Static Assets

Egg has a built-in plugin called static.
In production, it is recommended that you deploy static assets to CDN instead of using this plugin.

static maps /public/* to the directory app/public/* by default.

In this case, we just need to put our static assets into the directory app/public.

  1. app/public
  2. ├── css
  3. └── news.css
  4. └── js
  5. ├── lib.js
  6. └── news.js

Add Templates for Rendering

In most cases, data are usually read, processed and rendered by the templates before being presented to the user.
Thus we need to introduce corresponding template engines to handle it.

Egg does not force to use any particular template engines,
but specifies the View Plug-ins Specification
to allow the developers to use different plug-ins for their individual needs instead.

For more information, cf. View.

In this example, we will use Nunjucks.

First install the corresponding plug-in egg-view-nunjucks.

  1. $ npm i egg-view-nunjucks --save

And enable it.

  1. // config/plugin.js
  2. exports.nunjucks = {
  3. enable: true,
  4. package: 'egg-view-nunjucks'
  5. };
  1. // config/config.default.js
  2. exports.keys = <YOUR_SECURITY_COOKE_KEYS>;
  3. // add view's configurations
  4. exports.view = {
  5. defaultViewEngine: 'nunjucks',
  6. mapping: {
  7. '.tpl': 'nunjucks',
  8. },
  9. };

Carefully! config dir, not app/config!

Then create a template for the index page.
This usually goes to the app/view directory.

  1. <!-- app/view/news/list.tpl -->
  2. <html>
  3. <head>
  4. <title>Egg HackerNews Clone</title>
  5. <link rel="stylesheet" href="/public/css/news.css" />
  6. </head>
  7. <body>
  8. <ul class="news-view view">
  9. {% for item in list %}
  10. <li class="item">
  11. <a href="{{ item.url }}">{{ item.title }}</a>
  12. </li>
  13. {% endfor %}
  14. </ul>
  15. </body>
  16. </html>

Then add a controller and router.

  1. // app/controller/news.js
  2. const Controller = require('egg').Controller;
  3. class NewsController extends Controller {
  4. async list() {
  5. const dataList = {
  6. list: [
  7. { id: 1, title: 'this is news 1', url: '/news/1' },
  8. { id: 2, title: 'this is news 2', url: '/news/2' }
  9. ]
  10. };
  11. await this.ctx.render('news/list.tpl', dataList);
  12. }
  13. }
  14. module.exports = NewsController;
  15. // app/router.js
  16. module.exports = app => {
  17. const { router, controller } = app;
  18. router.get('/', controller.home.index);
  19. router.get('/news', controller.news.list);
  20. };

Open a browser window and navigate to http://localhost:7001/news.
You should be able to see the rendered page.

Tip:In development, Egg enables the development plug-in by default, which reloads your worker process when changes are made to your back-end code.

Create a Service

In practice, controllers usually won’t generate data on their own,
neither will they contain complicated business logic.
Complicated business logic should be abstracted as
a busineess logic layer instead, i.e., service.

Let’s create a service to fetch data from the
HackerNews.

  1. // app/service/news.js
  2. const Service = require('egg').Service;
  3. class NewsService extends Service {
  4. async list(page = 1) {
  5. // read config
  6. const { serverUrl, pageSize } = this.config.news;
  7. // use build-in http client to GET hacker-news api
  8. const { data: idList } = await this.ctx.curl(`${serverUrl}/topstories.json`, {
  9. data: {
  10. orderBy: '"$key"',
  11. startAt: `"${pageSize * (page - 1)}"`,
  12. endAt: `"${pageSize * page - 1}"`,
  13. },
  14. dataType: 'json',
  15. });
  16. // parallel GET detail
  17. const newsList = await Promise.all(
  18. Object.keys(idList).map(key => {
  19. const url = `${serverUrl}/item/${idList[key]}.json`;
  20. return this.ctx.curl(url, { dataType: 'json' });
  21. })
  22. );
  23. return newsList.map(res => res.data);
  24. }
  25. }
  26. module.exports = NewsService;

Egg has HttpClient built in in order to help you make HTTP requests.

Then slightly modify our previous controller.

  1. // app/controller/news.js
  2. const Controller = require('egg').Controller;
  3. class NewsController extends Controller {
  4. async list() {
  5. const ctx = this.ctx;
  6. const page = ctx.query.page || 1;
  7. const newsList = await ctx.service.news.list(page);
  8. await ctx.render('news/list.tpl', { list: newsList });
  9. }
  10. }
  11. module.exports = NewsController;

And also add config.

  1. // config/config.default.js
  2. // add news' configurations
  3. exports.news = {
  4. pageSize: 5,
  5. serverUrl: 'https://hacker-news.firebaseio.com/v0',
  6. };

Add Extensions

We might encounter a small problem here.
The time that we fetched are Unix Time format,
whereas we want to present them in a more friendly way to read.

Egg provides us with a quick way to extend its functionalities.
We just need to add extension scripts to the app/extend directory.
For more information, cf. Extensions.

In the case of view, we can just write a helper as an extension.

  1. $ npm i moment --save
  1. // app/extend/helper.js
  2. const moment = require('moment');
  3. exports.relativeTime = time => moment(new Date(time * 1000)).fromNow();

Then use it in the templates.

  1. <!-- app/view/news/list.tpl -->
  2. {{ helper.relativeTime(item.time) }}

Add Middlewares

Suppose that we wanted to prohibit accesses from Baidu crawlers.

Smart developers might quickly guess that we can achieve it by adding a middleware
that checks the User-Agent.

  1. // app/middleware/robot.js
  2. // options === app.config.robot
  3. module.exports = (options, app) => {
  4. return async function robotMiddleware(ctx, next) {
  5. const source = ctx.get('user-agent') || '';
  6. const match = options.ua.some(ua => ua.test(source));
  7. if (match) {
  8. ctx.status = 403;
  9. ctx.message = 'Go away, robot.';
  10. } else {
  11. await next();
  12. }
  13. }
  14. };
  15. // config/config.default.js
  16. // add middleware robot
  17. exports.middleware = [
  18. 'robot'
  19. ];
  20. // robot's configurations
  21. exports.robot = {
  22. ua: [
  23. /Baiduspider/i,
  24. ]
  25. };

Now try it using curl localhost:7001/news -A "Baiduspider".

See Middleware for more details.

Add Configurations

When writing business logic,
it is inevitable that we need to manage configurations.
Egg provides a powerful way to manage them in a merged configuration file.

  • Environment-specific configuration files are well supported, e.g. config.local.js, config.prod.js, etc.
  • Configurations could be set wherever convenient, e.g. near Applications/Plug-ins/Framesworks, and Egg will be careful to merge and load them.
  • For more information on merging, see Configurations.
  1. // config/config.default.js
  2. exports.robot = {
  3. ua: [
  4. /curl/i,
  5. /Baiduspider/i,
  6. ],
  7. };
  8. // config/config.local.js
  9. // only read at development mode, will override default
  10. exports.robot = {
  11. ua: [
  12. /Baiduspider/i,
  13. ],
  14. };
  15. // app/service/some.js
  16. const Service = require('egg').Service;
  17. class SomeService extends Service {
  18. async list() {
  19. const rule = this.config.robot.ua;
  20. }
  21. }
  22. module.exports = SomeService;

Add Unit Testing

Unit Testing is very important, and Egg also provides egg-bin to help you write tests painless.

All the test files should be placed at {app_root}/test/**/*.test.js.

  1. // test/app/middleware/robot.test.js
  2. const { app, mock, assert } = require('egg-mock/bootstrap');
  3. describe('test/app/middleware/robot.test.js', () => {
  4. it('should block robot', () => {
  5. return app.httpRequest()
  6. .get('/')
  7. .set('User-Agent', "Baiduspider")
  8. .expect(403);
  9. });
  10. });

Then add npm scripts.

  1. {
  2. "scripts": {
  3. "test": "egg-bin test",
  4. "cov": "egg-bin cov"
  5. }
  6. }

Also install dependencies.

  1. $ npm i egg-mock --save-dev

Run it.

  1. $ npm test

That is all of it, for more detail, see Unit Testing.

Conclusions

We can only touch the tip of the iceberg of Egg with the above short sections.
Where to go from here? read our documentation to better understand the framework.

  • About Egg boilerplate type, See Boilerplate Type Description.
  • Egg provides a powerful mechanism for extending features. See Plugin.
  • Egg framework allows small or large teams to work together as fast as possible under the well-documented conventions and coding best practices. In addition, the teams can build up logics on top of the framework to better suit their special needs. See more on [Frameworks].(../advanced/framework.md).
  • Egg framework provides code reusabilities and modularities. See details at Progressive.
  • Egg framework enables developers to write painless unit testing with many plugins and community-powered toolings. The team should give it a try by using Egg unit testing without worrying about setting up the testing tooling but writing the testing logics. See Unit Testing.