Upgrade to Pro — share decks privately, control downloads, hide ads and more …

DatoCMS + Next.js でプレビュー機能付きブログを作る

semigura
December 09, 2021

DatoCMS + Next.js でプレビュー機能付きブログを作る

2021.12.9 ジャムジャム!!Jamstack_3【初心者歓迎LT大会】
https://twitter.com/semigura

semigura

December 09, 2021
Tweet

More Decks by semigura

Other Decks in Programming

Transcript

  1. ੴ֞ɹ঵ଠ࿠ 
 twitter: @semigura • גࣜձࣾGaji-Laboʹ2018೥͔Βॴଐ • React, TypeScript, Next.js

    Λۀ຿Ͱѻ͍ͬͯ·͢ • Netlify CMS + GatsbyJS ߏ੒ͷ 
 ίʔϙϨʔταΠτͷ࣮૷पΓ΋୲౰ • Headless CMSΛ৮Δͷ͕झຯ • ೣͱԻָ͕޷͖ DatoCMS + Next.js ͰϓϨϏϡʔػೳ෇͖ϒϩάΛ࡞Δ
  2. ࠓճͷςʔϚͱ΍ͬͨ͜ͱ 1. DatoCMS ͷ؅ཧը໘͔Β Next.js ͷϒϩάςϯϓϨʔτΛબ୒͠ 
 αΠτΛ deploy 2.

    ࡞੒͞Εͨ Repository Λ clone ͠ɺ 
 Next.js ଆͰϓϨϏϡʔػೳΛ࣮૷ 3. DatoCMS ଆͰϓϨϏϡʔΛ֬ೝͰ͖ΔϓϥάΠϯΛ௥Ճ DatoCMS + Next.js Ͱ ϓϨϏϡʔػೳ෇͖ϒϩάΛ࡞Δ DatoCMS + Next.js ͰϓϨϏϡʔػೳ෇͖ϒϩάΛ࡞Δ
  3. ࠓճ৮ͬͯΈͨߏ੒ͷ͝঺հ DatoCMS • API ϕʔε (GraphQL) ͷ Headless CMS •

    ؅ཧը໘͔Β๛෋ͳαϯϓϧϓϩδΣΫτΛબ୒Ͱ͖ɺσϓϩΠ·Ͱ Ͱ͖Δ DatoCMS + Next.js ͰϓϨϏϡʔػೳ෇͖ϒϩάΛ࡞Δ
  4. γʔΫϨοττʔΫϯΛ௨ͯ͠ ϓϨϏϡʔ؀ڥͷURLʹ ΞΫηεͨ͠ࡍʹɺ Next.jsͷػೳͷҰͭͰ͋Δ ϓϨϏϡʔϞʔυΛ༗ޮʹ͢Δ pages/api/preview.js // ϓϨϏϡʔAPI ϧʔτΛ࡞੒͢Δ export

    default async (req, res) => { // ϓϨϏϡʔ؀ڥʹΞΫηε͢ΔͨΊͷγʔΫϨοττʔΫϯ // APIͱCMS͚͕ͩ஌͍ͬͯΔඞཁ͕͋Δ const secret = process.env.NEXT_CMS_DATOCMS_PREVIEW_SECRET; // γʔΫϨοττʔΫϯ͕ؒҧ͍ͬͯΔͳΒ͹ Invalid token Λฦ͢ if (secret && req.query.secret !== secret) { return res.status(401).json({ message: "Invalid token" }); } // ϒϥ΢βʹϓϨϏϡʔϞʔυ༻ͷ Cookie Λઃఆ͢Δ // `res.setPreviewData` Λ࢖͏͜ͱͰϓϨϏϡʔϞʔυʹઃఆͰ͖Δ res.setPreviewData({}); // ϓϨϏϡʔϞʔυ͕༗ޮͷঢ়ଶͰϧʔτʹભҠ͢Δ res.writeHead(307, { Location: "/" }); res.end(); }; DatoCMS + Next.js ͰϓϨϏϡʔػೳ෇͖ϒϩάΛ࡞Δ 2. ࡞੒͞Εͨ Repository Λ clone ͠ɺNext.js ଆͰϓϨϏϡʔػೳΛ࣮૷
  5. ϓϨϏϡʔϞʔυͷ Cookie ͕ઃఆ ͞Ε͍ͯΔ getStaticProps ΛؚΉ ϖʔδΛϦΫΤετ͢Δ ͱɺ getStaticProps ͕(Ϗϧυ࣌Ͱ͸

    ͳ͘)ϦΫΤετ࣌ʹݺͼग़͞ΕΔɻ context.preview ΍ context.previewData ʹج͍ͮͯҟͳ ΔσʔλΛऔಘ͢ΔΑ͏ʹ getStaticProps Λߋ৽͢Δ͜ͱ͕Ͱ ͖Δɻ pages/posts/[slug].js 
 export async function getStaticProps(context) { // ϓϨϏϡʔϞʔυͰϖʔδʹΞΫηεͨ͠৔߹ɺcontext.preview ͸ true ʹͳΔ // context.preview͕trueͷ৔߹ɺ"/preview" ΛAPIΤϯυϙΠϯτʹ௥Ճ ͢Δ // ެ։͞Εͨσʔλͷ୅ΘΓʹԼॻ͖σʔλΛϦΫΤετ͢Δ let endpoint = "https://graphql.datocms.com"; if (preview) { endpoint += `/preview`; } } DatoCMS + Next.js ͰϓϨϏϡʔػೳ෇͖ϒϩάΛ࡞Δ 2. ࡞੒͞Εͨ Repository Λ clone ͠ɺNext.js ଆͰϓϨϏϡʔػೳΛ࣮૷
  6. 3. DatoCMS ଆͰϓϨϏϡʔΛ֬ೝͰ͖ΔϓϥάΠϯΛ௥Ճ • ϓϨϏϡʔURLΛखಈͰୟ͖ͨ͘ͳ͍ • CMS্ͰϓϨϏϡʔ͕֬ೝͰ͖ΔΑ͏ʹͳ͍͍ͬͯͨ ͷͰ… Next.js Preview

    Links Λ௥Ճ https://www.datocms.com/marketplace/plugins/i/datocms-plugin- nextjs-preview DatoCMS + Next.js ͰϓϨϏϡʔػೳ෇͖ϒϩάΛ࡞Δ
  7. ײ૝ • DatoCMS ͸ Headless CMS Λબఆ͢Δ࣌ͷީิʹͳΓ͏Δ • ϝϦοτɿςϯϓϨʔτ͔ΒσϓϩΠ͕؆୯ʹͰ͖Δ •

    σϝϦοτɿ೔ຊޠͷ৘ใ͕͋·Γͳ͍ • Next.js ʹϓϨϏϡʔػೳ͕ϏϧτΠϯͰೖ͍ͬͯΔͷ͕ศར • Next.js ͕SSGͱͯ͠΋࢖͑Δͷ͕͏Ε͍͠ • ϓϨϏϡʔػೳ࣮૷͸υΩϡϝϯτΛ͋ͨΕ͹ͦΕ΄Ͳ೉͘͠͸ͳ͍ DatoCMS + Next.js ͰϓϨϏϡʔػೳ෇͖ϒϩάΛ࡞Δ