Next.js 9でSSR


はじめに

ReactでSSR(Server Side Rendering)フレームワークとしてNext.jsは有名です。

Next.jsの新しい特性

  • Built-in Zero-Config TypeScript Support: Build your application with increased confidence, thanks to automatic TypeScript support and integrated type-checking.
  • File system-Based Dynamic Routing: Express complex application routing requirements through the file system without the need for a custom server.
  • Automatic Static Optimization: Create ultra-fast websites that leverage Server-Side Rendering and Static Prerendering by default without compromising on features.
  • API Routes: Quickly build back-end application endpoints, leveraging hot-reloading and a unified build-pipeline.
  • More Production Optimizations: Applications are more responsive than ever thanks to in-viewport prefetching and other optimizations.
  • Improved DX: Unobtrusive, ease-of-use improvements to help you develop at your best.

出典:https://nextjs.org/blog/next-9

デモプロジェクト作成してみる

インストール

フォルダー「nextjs-demo」を作成し、npm initを実行後、npm install --save next react react-domを実行

package.jsonファイル修正

package.json
"scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
}

pagesフォルダーにファイル作成

./pages/index.jsファイルに

index.js
function Home() {
    return <div>ようこそ</div>
}

export default Home

next.js起動

npm run dev

アクセス

これで一番シンプルのページができました。

Typescriptに変更

npm install --save-dev typescript @types/react @types/node
mv pages/index.js pages/index.tsx
npm run dev

これでTypescript形式でもアクセスできます。

typescriptも自動インストールのようですが、私のPCはエラーがあって手動でインストールしました。

Router

Next.jsはpagesディレクトリのファイル、サブディレクトリのファイルをアクセスできます。

URLのpathにパラメータを渡したい場合は、正規表現の感じで動的にマッピングする必要があります。
このニーズでも問題ありません。

express.jsではよくある「/xxx/:id」の形式は、next.jsは「pages/xxx/[id].js」を作成して対応できます。

サンプル: /mypage/:userId

pagesディレクトリに「mypage」フォルダーを作成し、「mypage」の中で「[userId].js」のファイルを作成

[userId].js
import React from 'react';
class MyPage extends React.Component {
    static async getInitialProps({ query }) {
        const { userId } = query

        return { userId }
    }

    constructor(props) {
        super(props);
        this.state = {
            userId: props.userId
        }
    }

    render() {
        return (
            <div>
                URLのPathからuserId: {this.state.userId}
            </div>
        )
    }
}

export default MyPage

アクセス

[userId].jsのコードの結果を正しく表示されました。

これでURLとファイルの作成はもっと理解しやすくなります。

簡単にデモをやってみました。

以上