決済などどうしてもバックエンドで回したい処理をSPAに組み込みたいときのため、Netlify functionsとNuxt.jsを組みわせる方法をご紹介します。
Netlify FunctionsはAWS LambdaをNetlifyでホストしているアプリから簡単に使えるようにしてくれるものです。
AWSアカウントは不要、無料枠(125000アクセス/月, 100時間/月)もあるので気軽に試す事ができます。
API Gatewayの設定も要らないので楽すぎますね・・・
Nuxtアプリはもう作ってあるものとします。
npm install netlify-lambda
プロジェクトディレクトリ直下にfunctions/ping.jsを作成
mkdir functions
cd functions
touch ping.js
ping.jsを実装
export const handler = (event, context, callback) => {
const headers = {
'Access-Control-Allow-Origin': 'http://localhost:3000',
'Access-Control-Allow-Headers': 'Content-Type'
}
callback(null, {
statusCode: 200,
headers,
body: JSON.stringify({ message: 'Pong!' })
})
}
Nuxt(Vue)からaxiosでアクセスする部分を実装
plugins/APIClient.jsimport axios from 'axios'
const baseURL = `${process.env.NODE_ENV !== 'production' ? 'http://localhost:9000' : ''}/.netlify/functions`
const getAxios = () => {
return axios.create({
baseURL
})
}
export const ping = async () => {
const res = await getAxios().get('/ping')
return res.data
}
pages/index.vue<template>hello</template>
<script>
import { ping } from '@/plugins/lib/APIHandler'
export default {
name: 'Index',
async mounted () {
const data = await ping()
console.log(data)
},
}
</script>
こんな感じで最低限実装し、コンソールに{ message: 'Pong!' }が出ればよしとします。
package.json編集
npm run dev-apiで、開発環境でfunctionsが立ち上がるように修正npm run buildでfunctionsもビルドされるように修正"dev": "nuxt",
"dev-api": "netlify-lambda serve functions",
"build": "netlify-lambda build functions && nuxt build",
netlify.toml作成
プロジェクトルートにnetlify.tomlを作成し、以下記述
[build]
Command = "npm run build"
functions = "functions/dist"
publish = "dist"
ローカル動作確認
以下のコマンドで、localhost:3000でNuxtが、localhost:9000でAPIが立ち上がります。
npm run dev
# 別シェルで
npm run dev-api
本番動作確認
Netlifyとリンクしたmasterにマージして、Netlifyにデプロイしてみましょう。ローカル同様に動作する事が確認できます。