<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Valentijn Nieman on Medium]]></title>
        <description><![CDATA[Stories by Valentijn Nieman on Medium]]></description>
        <link>https://medium.com/@valentijnnieman_79984?source=rss-e005273bade------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R2AppfRsUQVwcOpciSg1mg.jpeg</url>
            <title>Stories by Valentijn Nieman on Medium</title>
            <link>https://medium.com/@valentijnnieman_79984?source=rss-e005273bade------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 21:08:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@valentijnnieman_79984/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Apollo + Next.js, authentication and CSRF protection]]></title>
            <link>https://medium.com/@valentijnnieman_79984/apollo-next-js-authentication-and-csrf-protection-4d897b9a703f?source=rss-e005273bade------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d897b9a703f</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[apollo-client]]></category>
            <category><![CDATA[csrf]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Valentijn Nieman]]></dc:creator>
            <pubDate>Tue, 24 Apr 2018 11:47:57 GMT</pubDate>
            <atom:updated>2018-04-24T11:47:57.786Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*JiTff85gB4lKHtAhykBGKQ.png" /></figure><p>At my previous job, we were working on a project for a client where we wanted to try out writing a backend GraphQL server and connect to it from a Apollo and React frontend. I also read about this cool thing called<a href="https://auth0.com/blog/building-universal-apps-with-nextjs/"> universal rendering</a>, and wanted to try out Next.js. We ran into some difficulties setting up and understanding how authentication should work with this set up, so I thought I’d write our journey of discovery down here, might it help others in a similar situation!</p><p>The specification I got for authentication from the back end developer who build the GraphQL server (in Java) was the following: A login mutation is available, which takes a username and password, that will return a JSESSIONID token, which is used in the back end for sessions. On the /graphql endpoint though — where the mutation is being sent to — a valid CSRF token should be sent along with every request.</p><p>We had a small discussion about if the CSRF token was actually needed, and decided it would be, because of the project’s nature (should be secure!) and because Spring Boot’s documentation specified it.</p><p>I started writing my front end code, utilising Next.js’ server side rendering, and thinking about how getting the data from the GraphQL server should work on the server side. I found <a href="https://dev-blog.apollodata.com/whats-next-js-for-apollo-e4dfe835d070">this article</a> very helpful, and the example that comes with it. I also found that <a href="https://github.com/zeit/next.js/tree/canary/examples">Next.js has a great number of well written examples</a> on his Github page. <strong>Most if not all of what I ended up using was taken straight from these examples, from the </strong><a href="https://github.com/zeit/next.js/tree/canary/examples/with-apollo-auth"><strong>with-apollo-auth</strong></a><strong> example in particular. </strong>I just tweaked it a little bit.</p><p>In these examples, a <a href="https://reactjs.org/docs/higher-order-components.html">HOC</a> called withData is used to create components with data coming from the GraphQL server. The HOC determines if the component passed in is being rendered server side or client side, and sets up an Apollo client via the initApollo method accordingly. It passes cookies along to this function, for the purpose of passing along authentication tokens. Perfect! The cookies are gotten from a parseCookies method, which again checks if we’re on the server or client (if context.req and context.req.headers are set, we have a request object coming from a browser, so we’re on the server. If we would be on the client side, these objects would not exist.)</p><p>In the initApollo function, we use create to create an Apollo client. Here, we’re creating an httpLink object, that specifies what Apollo will use for every request to the GraphQL endpoint. The documentation is <a href="https://www.apollographql.com/docs/link/">here</a>. We create a link, pass in our uri — the URL of our /graphQL endpoint — and set credentials to include. This last bit will specify that Apollo will <strong>include the headers it gets in the response from the server</strong>. In our case, this was the JSESSIONID token. We also create an authLink object that will hold the header data, and here we can specify extra stuff like an X-XSRF-TOKEN header, which Spring Boot will pick up as a CSRF token (in the Next.js example they set a Bearer token here, which is also a good idea). This token is gotten from the getToken() method which was passed in by our withData HOC.</p><p>In our case, we had a /csrf endpoint, that when receiving a GET request, would return a Set-Cookie header, which would set the XSRF-TOKEN as a cookie. Whether called from the client or server, these cookies would be set and gotten from the parseCookies method in withData, and be passed on to the initApollo function that could then set these values as headers in a Apollo Link object. My create method in the end looked like this:</p><pre>function create(initialState, { getToken }) {<br>  const httpLink = createHttpLink({<br>    uri: gql_url + &quot;/graphql&quot;,<br>    credentials: &quot;include&quot;<br>  });</pre><pre>const authLink = setContext((_, { headers }) =&gt; {<br>    const token = getToken()[&quot;XSRF-TOKEN&quot;];<br>    return {<br>      headers: {<br>        ...headers,<br>        &quot;X-XSRF-TOKEN&quot;: token<br>      }<br>    };<br>  });</pre><pre>return new ApolloClient({<br>    connectToDevTools: process.browser,<br>    ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)<br>    link: authLink.concat(httpLink),<br>    cache: new InMemoryCache().restore(initialState || {})<br>  });<br>}</pre><p>At first, these examples can be pretty confusing, at least they were to me. But once you learn more about how it works, you’ll see that Apollo handles a lot of stuff for you, and once you have your Link object set up correctly, it will all work very smoothly!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d897b9a703f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build an audio streaming server in Go]]></title>
            <link>https://medium.com/@valentijnnieman_79984/how-to-build-an-audio-streaming-server-in-go-part-1-1676eed93021?source=rss-e005273bade------2</link>
            <guid isPermaLink="false">https://medium.com/p/1676eed93021</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[streaming]]></category>
            <dc:creator><![CDATA[Valentijn Nieman]]></dc:creator>
            <pubDate>Tue, 03 Apr 2018 15:19:16 GMT</pubDate>
            <atom:updated>2018-04-24T09:33:53.200Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*P0sFFyitrn2MxBeDrnir4Q.png" /><figcaption>Look at that little musical Gopher!</figcaption></figure><p>Audio in the browser is not always welcomed with open arms. With most videos shared on social media now anticipating people watching them with the sound turned off, homepages with background music automatically playing (RIP Geocities) long forgotten, and buttons on the web that make an audible ‘click’ sound a thing that never took off, the web is pretty quiet.</p><p>However, streaming audio, either on demand or live, has never been more popular; services like Spotify, Twitch, and video-calling software like Skype or Discord all transform the sounds we humans make to 1’s and 0’s and send them to listeners across the world via the web. Surprisingly, not a whole lot of information on how to do this is available online, at least not aimed at beginners.</p><p>Lo and behold: “How to build an audio streaming server”, aimed to get people like me who have some knowledge of audio and/or music and a basic understanding of how the web works excited about streaming and digital audio in general.</p><p>Here, we will focus on building a very simple server that gets audio from one place to the other, via the magic of http. This server will get audio input from any available audio input on the server, like your Macbook’s microphone if you’re running the server on a Macbook, convert it to binary, and send out a chunked response to the client. Chunking the response in http is a way of sending out partials of data, or “chunks” of data, which is especially handy if you have a data set that is not complete yet. Think about it: when you are recording, you don’t have a complete recording yet, because you are still recording. Whenever you would stop recording, that’s when you have a complete recording in the form of a .wav or .mp3 file. We are interested in sending out the data <em>before</em> we are done recording, i.e., before we have a completed ‘recording.wav’ file.</p><p>We will use Go for this little project, as I find it is the perfect fit for a small, simple http server that doesn’t need a whole lot of setup to work. We’ll also use a library called <a href="https://github.com/gordonklaus/portaudio">Portaudio</a> that will handle all audio I/O. This is handy because it will handle audio regardless of the server’s OS (OSX/Windows/Linux). Portaudio works with a main audio loop where you will do something with the audio input and output. In this case, we only want the input - the output would be the server’s speakers (or whatever main audio output is set up on the server) which we don’t need. We are interested in saving the audio input into a buffer, which we can then push out via http. Our main loop (and Portaudio setup) looks like this:</p><pre>package main</pre><pre>import (<br> &quot;encoding/binary&quot;<br> &quot;github.com/gordonklaus/portaudio&quot;<br> &quot;net/http&quot;<br>)</pre><pre>const sampleRate = 44100<br>const seconds = 1</pre><pre>func main() {<br> portaudio.Initialize()<br> defer portaudio.Terminate()<br> buffer := make([]float32, sampleRate * seconds)<br> stream, err := portaudio.OpenDefaultStream(1, 0, sampleRate,   len(buffer), func(in []float32) {<br>  for i := range buffer {<br>   buffer[i] = in[i]<br>  }<br> })</pre><pre> if err != nil {<br>   panic(err)<br> }<br> stream.Start()<br> defer stream.Close()<br>}</pre><p>We first Initialize()portaudio, and deferTerminate(). We will then create a buffer slice, and set it to the same length as our sample rate will be. The <a href="https://en.wikipedia.org/wiki/Sampling_(signal_processing)#Sampling_rate">sample rate</a> will determine how many samples one second of audio will contain, so setting the buffer to the same sample rate means it will contain one second of audio. We then set up a default stream (meaning it will use the default input and output, or in this case, only the input) with <a href="https://godoc.org/github.com/gordonklaus/portaudio#OpenDefaultStream">OpenDefaultStream()</a>, with one input, zero outputs, a sample rate of 44100 and we specify our frames per buffer to be the length of our earlier created buffer. Then we pass in a function that has our input as an argument, which will be the main audio loop. Here, we simply map the values contained in the in array to our buffer array. Finally, we start the stream and defer stream.Close() when done.</p><p>Then, we can create a simple route /audio that will send out the buffer as a chunked response. We create a http.Flusher used by Go to send out chunks of data, and we set the Transfer-Encoding header to &quot;chunked&quot;. We create an infinite loop where we encode the buffer to binary and write it out to the stream.</p><pre>http.HandleFunc(&quot;/audio&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  flusher, ok := w.(http.Flusher)<br>  if !ok {<br>   panic(&quot;expected http.ResponseWriter to be an http.Flusher&quot;)<br>  }</pre><pre>  w.Header().Set(&quot;Connection&quot;, &quot;Keep-Alive&quot;)<br>  w.Header().Set(&quot;Transfer-Encoding&quot;, &quot;chunked&quot;)</pre><pre>  for true {<br>   binary.Write(w, binary.BigEndian, &amp;buffer)<br>   flusher.Flush() // Trigger &quot;chunked&quot; encoding<br>   return<br>  }<br> })</pre><p>Now we have a very basic audio streaming program, that captures audio from the default input of your computer, and makes it available for download via chunked encoding. Let’s dive into handling the audio on the client side next!</p><p>We’ll again use Go and Portaudio to create a little program that GET&#39;s the raw binary data from our /audio endpoint, decodes it, and plays it back using Portaudio. It works pretty much the same as our previous program, except it writes audio to a default output instead of reading from a default input. It looks like this:</p><pre>import (<br> &quot;bytes&quot;<br> &quot;encoding/binary&quot;<br> &quot;fmt&quot;<br> &quot;github.com/gordonklaus/portaudio&quot;<br> &quot;io/ioutil&quot;<br> &quot;net/http&quot;<br> &quot;time&quot;<br>)</pre><pre>const sampleRate = 44100<br>const seconds = 1</pre><pre>func main() {<br> portaudio.Initialize()<br> defer portaudio.Terminate()<br> buffer := make([]float32, sampleRate * seconds)</pre><pre>stream, err := portaudio.OpenDefaultStream(0, 1, sampleRate, len(buffer), func(out []float32) {<br>  resp, err := http.Get(&quot;<a href="http://localhost:8080/audio">http://localhost:8080/audio</a>&quot;)<br>  chk(err)<br>  body, _ := ioutil.ReadAll(resp.Body)<br>  responseReader := bytes.NewReader(body)<br>  binary.Read(responseReader, binary.BigEndian, &amp;buffer)<br>  for i := range out {<br>   out[i] = buffer[i]<br>  }<br> })<br> chk(err)<br> chk(stream.Start())<br> time.Sleep(time.Second * 40)<br> chk(stream.Stop())<br> defer stream.Close()<br>}</pre><pre>func chk(err error) {<br> if err != nil {<br>  panic(err)<br> }<br>}</pre><p>we use the ReadAll method from the ioutil package to read the body of the http response we’re getting from our server. To read the body, we also need a response reader, which we can get from the bytes package via NewReader(). We then use the Read() method from the binary package, which does the oppposite of the Write() method we used on our server. Finally, we map the contents of our read buffer to the output, which Portaudio will play back as beautiful, pristine sound.</p><p>Obviously this example is a little flawed — it will only get the next response from the /audio endpoint when the loop is finished, or when the buffer is finished playing. A great next step would be to get the response data asynchronously, maybe utilising a<a href="https://tour.golang.org/concurrency/1"> Go routine or channel</a>. Maybe the buffers need to be stored in an array of buffers, so that we can play them back one after the other! If you have thoughts on this, don’t be afraid to leave a comment.</p><p><a href="https://github.com/valentijnnieman/audio_streamer">You can find the full example code here!</a></p><p><em>Edit: I at first wanted to make this a multi-part series, but ultimately decided against it, mainly because of time constraints. Thanks for reading!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1676eed93021" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>